Is there a way to initialize the final field in the anonymous class?

In Java, we can initialize the final field in the constructors in both the base class and its subclasses, as well as in the built-in initialization block in the base class. However, it seems that we cannot initialize the final fields in the inline initialization block in the subclass. This behavior mainly affects anonymous classes from which super constructors cannot 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 a way to initialize the final inherited field in the anonymous class?

Comment This question does not concern constructors, but the final field initialization.

+2
java inheritance final
Apr 04 '16 at 19:20
source share
2 answers

You must initialize the final instance variables either at the time of declaration or in the constructor. However, you can provide a 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 to use the default value.

+5
Apr 04 '16 at 19:28
source share

Final instance variables must be initialized in the 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; } } 
+1
Apr 04 '16 at 19:26
source share



All Articles