CONSTRUCTOR CHAIN

 
Constructor chaining occurs through the use of inheritance. A subclass constructor method's first task is to call its super class' constructor method. This ensures that the creation of the subclass object starts with the initialization of the classes above it in the inheritance chain.
There could be any number of classes in an inheritance chain.
Every constructor method will call up the chain until the class at the top has been reached and initialized. Then each subsequent class below is initialized as the chain winds back down to the original subclass. This process is called constructor chaining.
Use this() to call another constructor in the same class.
super () to call another constructor in the super class
In case we want to call another constructor, this()/super() should be the first line in the constructor.
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
class  P {
    P(){
        System.out.println("P()");
        }   
    }
class  Q extends P
    {
        Q()
            {
                System.out.println("Q()");
            }
    }
class  R extends Q
    {
        R()
            {
                System.out.println("R()");
            }
    }
class ConstructorChain 
    {
        public static void main(String[]  args)
            {
                P p1 = new P();
                System.out.println("------------");
                Q q1 = new Q();
                System.out.println("------------");
                R r1 = new R();
            }
    }

O/P:

ConstructorChain