Win a copy of Learn Spring Security (video course) this week in the Spring forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

A constructors puzzle.

 
Dmitry Zhuravlev
Ranch Hand
Posts: 93
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 5575
Eclipse IDE Java Windows XP
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
*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
Saloon Keeper
Pie
Posts: 2264
76
Android Chrome Eclipse IDE
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 256
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic