Thursday, 17 July 2014

Why creating an object of the sub class invokes also the constructor of the super class?


class Super {
    String s;
 
    public Super(){
     System.out.println("Super");
    }
}
 
public class Sub extends Super {
 
    public Sub(){
     System.out.println("Sub");
    }
 
    public static void main(String[] args){
     Sub s = new Sub();
    }
}
It prints:
Super
Sub
When inheriting from another class, super() has to be called first in the constructor. If not, the compiler will insert that call. This is why super constructor is also invoked when a Sub object is created.
This doesn't create two objects, only one Sub object. The reason to have super constructor called is that if super class could have private fields which need to be initialized by its constructor.
After compiler inserts the super constructor, the sub class constructor looks like the following:
    public Sub(){
     super();
     System.out.println("Sub");
    }

No comments:

Post a Comment