我有一个最终定义的类变量,该变量在构造函数中设置。当我在构造函数中检查抽象类和子类的值时,它是正确的值。但是当我以后用某种方法检查它时,它总是错误的。这是我的代码。
abstract class AbstractArticleObject extends StructureObject {
final boolean firstArticle;
AbstractArticleObject(Element element, boolean firstArticle) {
super(element);
this.firstArticle = firstArticle;
...
}
}
class ArticleObject extends AbstractArticleObject {
ArticleObject(Element element, boolean firstArticle) {
super(element, firstArticle);
// In this method, firstArticle is whatever was passed in, which is sometimes true.
Log.v(title, String.format(String.valueOf(this.firstArticle));
}
@Override
StructureState getState() {
// In this method, firstArticle is always false.
Log.v(title, String.format(String.valueOf(firstArticle));
if (...) {
...
} else if (...) {
if (firstArticle) {
return StructureState.CAN_OPEN;
} else {
...
}
}
return StructureState.NOT_SET;
}
}
如果我在构造函数中设置值,并且该值是最终值,为什么即使将其设置为true也返回false?
答案 0 :(得分:1)
getState()
是从哪里来的?
如果final
变量在初始化之前进行访问,则它们可能会“更改”。考虑以下微型程序:
public class Test {
private final boolean value;
public Test() {
doSomething();
this.value = true;
doSomething();
}
private void doSomething() {
System.out.println(value);
}
public static void main(String[] args) {
new Test();
}
}
该程序的输出为
false
true
因此,如果您的getState()
方法是从例如StructureObject
的构造函数,那么它将在AbstractArticleObject
构造函数初始化firstArticle
之前被调用,并且它将是false
。