Tuesday, March 4, 2014

Which Constructors are called?

public class First {
    public First(){
        super();
        System.out.println("First... No Actually Second");
    }
}

public class Second extends First {
    public Second(){
        super();
        System.out.println("Second...No third");
    }
    public static void main(String[] args) {
        Second second= new Second();
    }
}

Will this code run? Answer to that is YES.

OUTPUT : 

First... No Actually Second
Second...No third

Why highlighted statement super() in First class does not give an error?

As we create an object of Subclass'Second', constructors are called in the order of creation of classes. Second() makes call to First() before it executes the instructions in Second(). First() makes a call to its Super class constructor Object()  which is Universal Super class of all Java Objects.

No comments:

Post a Comment