Yesterday I ran into an interesting problem, and although the fix was pretty simple, I'm still a little blurry about the why.
I have a class that has a private member variable that is assigned when it is created, however, if it is used in an abstract function called by the superclass constructor, the variable does not matter. The solution to the problem was quite simple, I just had to declare the variable as static, and it was assigned correctly. Some code to illustrate the problem:
class Foo extends BaseClass { private final String bar = "fooBar!"; public Foo() { super(); } @Override public void initialize() { System.out.println(bar); } }
And base class:
abstract class BaseClass { public BaseClass() { initialize(); } public abstract void initialize(); }
In this example, when we call new Foo(); , it outputs (null) instead of the expected fooBar!
Since we are creating an object of type Foo, should its members not be allocated and assigned before calling its (and therefore its superclass) constructor? Is this indicated somewhere in the Java language or specifically the JVM?
Thank you for understanding!
source share