Re: Constructor Chaining Conundrum
- From: rnurse@xxxxxxxxx
- Date: 1 Jun 2006 07:28:51 -0700
Ahh, the fog has lifted. I added a new method to the Base class: one
that is not overriden by the child. I then have the Base constructor
call it instead.
Base()
{
// print( );
anotherPrint();
}
void anotherPrint( )
{
System.out.println("Super " + s);
}
Now, I'm getting the behavior I was expecting. I'm studying for the
SCJP and this was one of the Whizlabs testing simulator
(www.whizlabs.com) questions. Thanks for your help and those links.
I'll also be using my debugger as a study aid too.
Hendrik Maryns wrote:
Why doesn't this surprise me? Have you ran it through a debugger? You
will see exactly what happens: s in Derived *shadows* s in Base, whereas
print() in Derived *overrides* print() in Base; thus if Base's
constructor calls print(), Derived's print() will be called (we are
creating a Derived, after all, the unnecessary cast doesn't change
anything at that, that's polymorphism at work), which uses its own s,
shadowing Base's s, and at that point, the initialisation of s, which
happens *after* calling super(), has not yet been done, thus Derived.s
is null, and you get Sub null in the console.
This is all like it should be. Golden rule: do not call methods in a
constructor which can be overridden in a subclass.
Also see http://mindprod.com/jgloss/constructor.html#INITIALISATION and
http://mindprod.com/jgloss/shadow.html
H.
.
- References:
- Constructor Chaining Conundrum
- From: rnurse
- Re: Constructor Chaining Conundrum
- From: Hendrik Maryns
- Constructor Chaining Conundrum
- Prev by Date: Re: Email send retry
- Next by Date: Re: EnumSet + contains: strange behavior
- Previous by thread: Re: Constructor Chaining Conundrum
- Next by thread: Re: Constructor Chaining Conundrum
- Index(es):
Relevant Pages
|