12/14/2008

Constructor chaining


Initialization of each constructor starts one by one as it is called. After the process reaches the Object class initialization, then in the reverse order, each class starts its initializing operation written in its constructor and finishes it.

<Sample>
class Sample {
    Sample() {
        // super() is generated and the constuctor of the Object class is called
        System.out.println("No-argument constructor");
    } 
    Sample(int x) {
        this();     // No-argument constructor is called
        System.out.println("Constructor");
    }
    public static void main(String[] args) {
        Sample sp = new Sample(1);
    }
}


<Result>
No-argument constructor
Consturctor