• 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
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

this() and super()

 
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi all,

Can someone verify that this() and super() can only be used inside constructors to specify which constructor to call in a situation where our code has several overloading constructors.

Thanks,

Rafal.
 
Ranch Hand
Posts: 1585
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi,

Overloaded constructors can call each other using "this", and if we have several overloaded constructors that call each other using "this", then the last called constructor will call the constructor of the super class.

The following code demonstares how it happens:



Giving the output:

In Parent
In Child(int x,int y)
In Child(int x)
In Child()

Because, when you instantiate an object of Child, its default constructor will be called, which in turn, will call the overloaded constructor with one parameters, which in turn, will call the overloaded constructor with two parameters, which finally will call the super constructor of the super class.

Now that these method calls have been placed in the call stack, the stack itself will be unwinded, giving a LIFO (Last In First Out) order, which will cause the output of "In Child(int x,int y)" first, "In Child(int x)" second, "In Child()" finally.

Best of luck ...
 
My name is Inigo Montoya, you killed my father, prepare to read a tiny ad:
a bit of art, as a gift, that will fit in a stocking
https://gardener-gift.com
reply
    Bookmark Topic Watch Topic
  • New Topic