Connecting Tech Pros Worldwide Help | Site Map

Inheritance and member variables

  #1  
Old June 21st, 2007, 02:45 PM
ITMozart
Guest
 
Posts: n/a
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?

Bye!
it
  #2  
Old June 21st, 2007, 04:05 PM
Lew
Guest
 
Posts: n/a

re: Inheritance and member variables


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
Closed Thread


Similar Threads
Thread Thread Starter Forum Replies Last Post
Multi-level inheritance and accessing base protected member variables Joseph Paterson answers 4 June 28th, 2007 03:05 PM
Can I inherit member variables? lm401@cam.ac.uk answers 17 September 22nd, 2006 10:35 AM
Inherit member variables? Joseph Turian answers 1 November 26th, 2005 08:25 AM
Class Member Variables:instance Vs pointer Mon answers 15 July 22nd, 2005 05:38 AM