• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Constructor rules...I don't get it

 
Greenhorn
Posts: 16
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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
 
Ranch Hand
Posts: 39
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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
 
Ranch Hand
Posts: 823
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator


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
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
reply
    Bookmark Topic Watch Topic
  • New Topic