Constructor Chaining using this and super keyword

By default super class constructors are not inherited in subclass.

  • Invoke super class constructor implicittly or explicitly by using super keyword.
  • The first line of sub class constructor must be super. If it is not explicitly written, compoler will automatically put super keyword as a first statement in subclass to invoke super class no-argument constructor
  • super keyword can be used to call super class methods or access datafields
  • Invoking a superclass constructor by its name cause a syntax error
  • this keyword is used to chain constructor in the same class
  • super keyword is used to chain subclass constructor to super class constructor

You can read more about this keyword from the following article. http://coding-guru.com/this-keyword/

Chaining Constructor using Super Keyword

Chaining Constructor using Super Keyword

Chaining ex1 -2

Chaining Constructor using Super Keyword

Output  of the above prgram: 

Creating a TubeLight object.
Returning from non-default constructor no. 3 in class Light
Returning from non-default constructor no. 2 in class TubeLight
Returning from non-default constructor no. 1 in class TubeLight

 

Constructor chaining with this keyword

Constructor chaining with this keyword

Output of the above Program :

Constructor 1 : default constructor
Constructor 2 : with one argument
Constructor 2 : with two arguments

Comments

  1. By Alex

    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.