Is there a way to initialize final field in anonymus class? [duplicate]

半世苍凉 提交于 2019-12-11 01:24:42

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!