This week's book giveaway is in the Mac OS forum.
We're giving away four copies of a choice of "Take Control of Upgrading to Yosemite" or "Take Control of Automating Your Mac" and have Joe Kissell on-line!
See this thread for details.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Constructor rules...I don't get it Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Constructor rules...I don Watch "Constructor rules...I don New topic
Author

Constructor rules...I don't get it

Scott Ramsey
Greenhorn

Joined: Jun 28, 2001
Posts: 16
For constructors, the rule is: you cannot refer to any instance methods or variables until the constructor for the class' superclass has completed. But what explains the following code...



The resulting output is:

SuperClass constructor START
SuperClass doStuff()
SuperClass constructor FINISH


SuperClass constructor START
SubClass doStuff(); num = 444
SuperClass constructor FINISH

SubClass constructor; num = 444


I don't get it. This means that the subclass has had an instance method called and an instance variable initialized BEFORE its constructor is even called!

Anybody see what I'm missing here?

Thanks


Scott<br />-----------------<br />SCJP, SCJD, SCWCD<br />XML, UML, WLS6.0
Pete Harris
Ranch Hand

Joined: Feb 05, 2003
Posts: 39
Scott,

I think this makes sense. The rule you mention is simply saying that there can be no statements in a constructor before an explicit call to it's superclass constructor. Obviously with implicit calls such as you have here, you can't anyway because the call is made automatically before the first statement executes.

Therefore, what it's disallowing is:


which will produca a compile time error.

cheers, Pete
Julian Kennedy
Ranch Hand

Joined: Aug 02, 2004
Posts: 823

Originally posted by Scott Ramsay
I don't get it. This means that the subclass has had an instance method called and an instance variable initialized BEFORE its constructor is even called!

As is implied by Pete's response the statement above is not actually true. The constructor of the subclass is invoked by new SubClass(). The first thing that the subclass constructor does is to implicitly invoke the superclass constructor.

It would be correct to say that the subclass has an instance method called before its constructor returns. This is a legal, if peculiar, case.

Jules
 
jQuery in Action, 2nd edition
 
subject: Constructor rules...I don't get it