This week's book giveaways are in the Refactoring and Agile forums.
We're giving away four copies each of Re-engineering Legacy Software and Docker in Action and have the authors on-line!
See this thread and this one for details.
Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Question about K&B SCJP6 Self Test (Chapter 2) question #12

 
mrinal utkarsh
Greenhorn
Posts: 8
Eclipse IDE Java Oracle
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Page #167 k&b scjp6



Here in the main() method, new House("x ") calls its constructor House(String name).
A constructor can either have a call to this() or super() (but not both).
Here in the constructor this() is explicitly defined, so does the compiler still insert super() to initialize it's base class??
Or how else it's done, please clarify. And suggest some good links to understand these topics properly.
Thank you!
 
Andrea Black
Ranch Hand
Posts: 52
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I'll probably butcher this explanation but nobody else is taking it so here goes…

Yeah. House's overloaded String constructor calls it's own no-arg constructor, which calls it's superclass's no-arg constructor. (Super's String constructor never gets called of course.)

S & B says "The first statement of every constructor must be a call to this() (an overloaded constructor) or super()." and also "The compiler will add a call to super() unless you have already put in a call to this() or super()." So I take that to mean that each overloaded constructor gets the compiler-added call. Even if one of the OTHER constructors already had a call to to super or this, like in this case.
 
Slim Soltani Dridi
Greenhorn
Posts: 20
Java Spring Windows
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
When the program start, it calls the main method and does "new House("x");
new House("x") call the constructor House(String name).
During the compilation, House(String name) saw the keyword "this" ... so it didn't add a super() keyword. If it's not the case, It add a super() keyword without ARGS !
The constructor House(String name) calls House() without arg ! And this constructor, because you didn't put a keyword at the beginning, add the super() keyword. And the super keyword refer to superclass Building() (which refer to superclass constructor of Object()).

You can go to the tutorial on the website of Oracle : http://docs.oracle.com/javase/tutorial/java/IandI/super.html
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic