• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Paul Clapham
  • Ron McLeod
  • Tim Cooke
  • Junilu Lacar
Sheriffs:
  • Rob Spoor
  • Devaka Cooray
  • Jeanne Boyarsky
Saloon Keepers:
  • Jesse Silverman
  • Stephan van Hulst
  • Tim Moores
  • Carey Brown
  • Tim Holloway
Bartenders:
  • Jj Roberts
  • Al Hobbs
  • Piet Souris

A constructors puzzle.

 
Ranch Hand
Posts: 93
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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?
 
Ranch Hand
Posts: 5575
Eclipse IDE Windows XP Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
 
Creator of Enthuware JWS+ V6
Posts: 3398
312
Android Eclipse IDE Chrome
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
 
Ranch Hand
Posts: 256
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
reply
    Bookmark Topic Watch Topic
  • New Topic