Thursday 25 September 2014

Session 12:- Constructor Chaining

 Why we use Constructor Chaining:-

  •  Any constructor of a class whether they are default or custom first executable statement is calling its immediate parent class, zero parameterized constructor.
  • The constructor chaining is required to initialize the resource or state of parent class. 
  •   In any constructor when we explicitly provide. “this” or “super” than implicitly super will be destroyed. 

NOTE:-

  •   We can’t have more than one “super” or we can’t have  more than “this”.
  •  We can’t have more than one “super” and one “this” at a same time. 
  • Constructor can’t call the same class constructor or super class constructor by name rather it has to call by using “super” or “this”.
  • “Super” or “this” must be first executable statement of the in case of constructor.
Example:- Constructor Chaining By using Super and this Keyword 
 
public class Grandfather {
public Grandfather(){
System.out.println ("Grandfather Constructor ");
 }
 }
public class Father extends Grandfather {
public Father(){
System.out.println("Father constructor");
 }
 }
public class Child extends Father {
public Child(){
System.out.println("Child constructor");
   }
  }
public class Guldu {
public static void main(String[] args) {
   new  Child();

}}  

 OUTPUT:- 

 Grandfather constructor 
 Father constructor 
 Child constructor

NOTE:-   

  • All the classes in java are the child class of java.lang. Object  
  • i.e. Object is most parent class
  • In java the moment when write class it automatically inherit java.lang. Object

No comments:

Post a Comment