Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does an instance of superclass get created when we instantiate an object?

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?

like image 413
Gaurav Avatar asked Jan 25 '12 16:01

Gaurav


People also ask

What happens when you instantiate an object?

Instantiate in Java means to call a constructor of a Class which creates an an instance or object, of the type of that Class. Instantiation allocates the initial memory for the object and returns a reference.

Can a superclass be instantiated?

When a subclass is instantiated, instantiate all the superclasses are instantiated at the same time. Here, the initialization of superclass attributes is ensured by the call of the superclass constructors, as described in Inheritance and Constructors.

What creates an instance of a class?

When you create an object, you are creating an instance of a class, therefore "instantiating" a class. The new operator requires a single, postfix argument: a call to a constructor. The name of the constructor provides the name of the class to instantiate. The constructor initializes the new object.

Can the superclass be instantiated in Java?

The superclass allows its subclasses unlimited instantiation and therefore also allow its protected instance constructor to be published.


1 Answers

A single object is created - but that object is an instance of both the superclass and the subclass (and java.lang.Object itself). 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 this reference will be the same for all of those constructors; they're all contributing to the initialization of the single object.

like image 120
Jon Skeet Avatar answered Oct 18 '22 15:10

Jon Skeet