I have a class variable that is final and is set in the constructor. When I check the value of it in the constructor for the abstract class and the subclass it's the correct value. But when I check it later in a method it's always false. Here's my code.
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;
}
}
If I'm setting the value in the constructor, and the value is final, why is it returning false even when it was set to true?
Where is getState()
called from?
It is possible for final
variables to "change" if you access them before they're ever initialized. Consider the following tiny program:
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();
}
}
The output of this program will be
false
true
So, if your getState()
method is called from e.g. the constructor of StructureObject
, then it will be called before the AbstractArticleObject
constructor initializes firstArticle
, and it will be false
.