aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes A constructors puzzle. Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Soft Skills this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "A constructors puzzle." Watch "A constructors puzzle." New topic
Author

A constructors puzzle.

Dmitry Zhuravlev
Ranch Hand

Joined: Apr 14, 2010
Posts: 93
Ladys and Gents, please help with the following:

I have an example code:


Output is
SUPER
SUPER 77
SUB77
SUB


I dont understand why! Its seems that SUPER should be printed twice: first when SubClass() is called in the beginning and then because of this() in the SuperClass(). But one of these two options doesn't work. Why? Which one?
Seetharaman Venkatasamy
Ranch Hand

Joined: Jan 28, 2008
Posts: 5575

*this()* calls the overloaded constructor of class itself ; and *super()* calls the super class constructor *according to the arguments* .

do you have any IDE like eclipse ? if yes, please debug the flow.

hth
Frits Walraven
Creator of Enthuware JWS+ V6
Bartender

Joined: Apr 07, 2010
Posts: 1731
    
  25

Hi Dmitry,

This is what happens:

constructor SubClass() is called
constructor SubClass(77) is called
constructor SuperClass(77) is called
constructor SuperClass() is called

from there going back
System.out.println("SUPER");
System.out.println("SUPER " + 77);
System.out.println("SUB" + 77);
System.out.println("SUB");

Regards,
Frits
bhanu chowdary
Ranch Hand

Joined: Mar 09, 2010
Posts: 256
You can have either this or super in a constructor. When you call it will go to the no-arg constructor SubClass(), but since in this constructor it will go into the args constructor of SubClass and not no-args constructor of SuperClass.
Hope this helps.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: A constructors puzzle.