ITMozart wrote:
Quote:
I wrote this piece of code:
>
>
class A {
public A() {
someMeth();
}
public void someMeth() {
out.println(entries[0]);
}
public final String[] entries = { "a" };
}
>
class B extends A {
public void someMeth() {
out.println(entries[0]); *** NullPTR
super.someMeth();
}
private final String[] entries = { "b" };
}
>
the point is to start, during instantiation, some methods from the
bottom of the inheritance tree instead of from the top.
>
but i had some unexpected behavior: at the marked point, I receive a
NullPTR.
Why does this happen?
>
Seem like that at the moment of the call (***) member vars are not
instantiated, since the call comes from the constructor of the
superclass, and the subclass is not still instantiated, but why then the
subclass method works?
The subclass method exists, but the subclass variables don't get initialized
until the superclass constructor finishes. During the call to the polymorphic
method someMeth() in the superclass constructor, you access the subclass
method which access the subclass 'entries' array, which still has its default
value of null because you have not entered the child class constructor yet.
Joshua Bloch covered this in /Effective Java/ when he advised that you not
call overridable methods in a constructor.
--
Lew