有没有办法初始化匿名类中的最终字段? [英] Is there a way to initialize final field in anonymus class?
问题描述
在Java中,我们既可以在基类及其子类的构造函数中,也可以在基类的内联初始化程序块中初始化final
字段.但是,似乎我们无法在子类的内联初始化程序块中初始化final
字段.此行为主要影响无法从其调用super
构造函数的匿名类.
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;
}
};
有什么方法可以初始化匿名类中继承的final
字段?
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.
推荐答案
您必须在声明过程中或在构造函数中初始化最终实例变量.但是,您可以将值提供给构造函数
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
这篇关于有没有办法初始化匿名类中的最终字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!