Jan 12, 2011

Constructor Chaining in JAVA

When you try to make an object of the subclass type, it will be running all the constructors in the inheritance tree.
Please see the below example...

public class Animal {
public Animal(){
System.out.println("Animal Constructor");
}
}

public class Hippo extends Animal {
public Hippo(){
System.out.println("Hippo Constructor");
}
}

public class ConstructorChainingTest {
public static void main(String[] args){
Hippo h = new Hippo();
}
}

If you run ConstructorChainingTest .java, the output would be
Animal Constructor
Hippo Constructor..

This is called Constructor Chaining in JAVA

No comments:

Post a Comment

Post a Comment

Note: Only a member of this blog may post a comment.