问题
In Java, we can initialize a final
field in constructors both in the base class and its subclasses, and also in an inline initializer block in the base class. However, it seems that we can not initialize final
fields in an inline initializer block in a subclass. This behavior mainly affects anonymous classes from which super
constructors can not be called.
abstract class MyTest {
final protected int field;
public MyTest() {
// default value
field = 0;
}
}
MyTest anonymTest = new MyTest() {
{
// Error: The final field MyTest.field cannot be assigned
field = 3;
}
};
Is there any way to initialize an inherited final
field in an anonymus class?
Comment: This question is not about constructors, but about final field initialization.
回答1:
You have to initialize final instance variables either during declaration or in the constructor. However, you can provide the value to the constructor
abstract class MyTest {
final protected int field;
public MyTest() {
// default value
this(0);
}
public MyTest(int f) {
field = f;
}
}
MyTest anonymTest = new MyTest(3) {
};
Update: Added constructor for using default value
回答2:
Final instance variables must be initialized in a constructor.
abstract class MyTest {
final protected int field;
public MyTest() {
// default value
field = 0;
}
public MyTest(int val)
{
// will set the final field to the specified val
field = val;
}
}
来源:https://stackoverflow.com/questions/36411092/is-there-a-way-to-initialize-final-field-in-anonymus-class