31 Oct 2014
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. https://coding-guru.com/this-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
Output of the above Program :
Constructor 1 : default constructor
Constructor 2 : with one argument
Constructor 2 : with two arguments
Very nice information. Keep it up