Saturday, April 23, 2011

Multilevel inheritance - Calling order of constructors

In case of multilevel of inheritance , Base class constructor is called 1st.

// Demonstrate when constructors are called.
// Create a super class.
class A {
    A() {
        System.out.println("Inside A's constructor.");
    }
}

// Create a subclass by extending class A.
class B extends A {

    B() {
        System.out.println("Inside B's constructor.");
    }

}

// Create another subclass by extending B.
class C extends B {
    C() {
        System.out.println("Inside C's constructor.");
    }
}

class CallingCons {

    public static void main(String args[]) {
        C c = new C();
    }

}

The output from this program is shown here:

Inside A’s constructor

Inside B’s constructor

Inside C’s constructor


No comments:

Post a Comment

Chitika