Does an instance of superclass get created when we instantiate a particular class in java. If that is the case then there would be a lot of overhead of instantiating all the super classes. I tried following code:
public class AClass {
public AClass() {
System.out.println("Constructor A");
}
}
public class BClass extends AClass{
public BClass(){
System.out.println("Constructor B");
}
}
public class Test {
public static void main(String[] args) {
BClass b = new BClass();
}
}
The output of the code is :
Constructor A
Constructor B
So, does it mean that the complete hierarchy of the objects of the superclasses get created when we instantiate a class?
A single object is created – but that object is an instance of both the superclass and the subclass (and
java.lang.Objectitself). There aren’t three separate objects. There’s one object with one set of fields (basically the union of all the fields declared up and down the hierarchy) and one object header.The constructors are executed all the way up the inheritance hierarchy – but the
thisreference will be the same for all of those constructors; they’re all contributing to the initialization of the single object.