jQuery in Action, 3rd edition
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

JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "A constructors puzzle." Watch "A constructors puzzle." New topic

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

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.

Frits Walraven
Creator of Enthuware JWS+ V6
Saloon Keeper

Joined: Apr 07, 2010
Posts: 2007

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 " + 77);
System.out.println("SUB" + 77);

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.
It's not a secret anymore!