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.