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?
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.
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.
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.
The superclass allows its subclasses unlimited instantiation and therefore also allow its protected instance constructor to be published.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With