File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Scjp Chapter2 Self Test Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Scjp Chapter2 Self Test" Watch "Scjp Chapter2 Self Test" New topic
Author

Scjp Chapter2 Self Test

Srinivas Palam
Ranch Hand

Joined: Oct 20, 2005
Posts: 51


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

Joined: Apr 16, 2003
Posts: 65
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

Joined: Oct 20, 2005
Posts: 51
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

Joined: Apr 16, 2003
Posts: 65
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);
}
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Scjp Chapter2 Self Test