Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Scjp Chapter2 Self Test

 
Srinivas Palam
Ranch Hand
Posts: 73
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


Can someone explain why the answer is b h hn x.
My understanding was since we are invoked constructor with single parameter, the answer should be bn x hn x.
 
Ryan Wilson
Ranch Hand
Posts: 65
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The code has the following flow

House(String name)
this() //calls the no-args constructor in House
House() //the compiler implicitly adds a call to parents no-args constructor, super()

Building's no-args constructor executes and prints b
then House's no-args constructor prints h
Then finally House(String name) constructor prints hn x

You would need to explicitly call super(name) from one of the House constructors to execute the overloaded constructor in Building
 
Srinivas Palam
Ranch Hand
Posts: 73
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Ryan. I have one more question.



If I replace this() with super(#2) why is it skipping printing h? What is the use of this(#1) in building class? It's just to call object constructor?
 
Ryan Wilson
Ranch Hand
Posts: 65
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Srinivas Palam wrote:If I replace this() with super(#2) why is it skipping printing h? What is the use of this(#1) in building class? It's just to call object constructor?

The first line in a constructor needs to be either a call to this or super. If neither of those are typed (meaning you explicitly add that code) then the compiler will add a call to the parents no-args constructor ( super();)
Furthermore one of the constructors in the class will eventually need to call super to instantiate the parent class.

So when you comment out the call to this() on line 12 and added the call to super there is no longer a need to execute the no-args constructor of House. Therefore "h" is not printed.
Regarding your second question, calling this(); on line 5 will simply call the no-args constructor. However in this sample code the Building(String name) overloaded constructor is never called.
Remember that the compiler will never call the super that contains parameters so this must be explicitly done
Example:
House(String name) {
// this();
super(name); #2
System.out.print("hn " + name);
}
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic