Inheritance and member variables

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • ITMozart

    #1

    Inheritance and member variables

    I wrote this piece of code:


    class A {
    public A() {
    someMeth();
    }
    public void someMeth() {
    out.println(ent ries[0]);
    }
    public final String[] entries = { "a" };
    }

    class B extends A {
    public void someMeth() {
    out.println(ent ries[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?

    Bye!
    it
  • Lew

    #2
    Re: Inheritance and member variables

    ITMozart wrote:
    I wrote this piece of code:
    >
    >
    class A {
    public A() {
    someMeth();
    }
    public void someMeth() {
    out.println(ent ries[0]);
    }
    public final String[] entries = { "a" };
    }
    >
    class B extends A {
    public void someMeth() {
    out.println(ent ries[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

    Comment

    Working...