Is a superclass instantiated when an object is created?

Whether a superclass is instantiated when instantiating a particular class in java. If so, then there will be a lot of overhead for instantiating all the superclasses. I tried the 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(); } } 

Code output:

 Constructor A Constructor B 

So, does this mean that a complete hierarchy of superclass objects is created when the class is instantiated?

+6
source share
3 answers

A single object is created, but this object is an instance of both the superclass and the subclass (and java.lang.Object itself). There are no three separate objects. There is one object with one set of fields (basically the union of all fields declared up and down the hierarchy) and one object header.

Constructors run right down to the inheritance hierarchy, but the this reference will be the same for all of these constructors; they all contribute to the initialization of a single object.

+8
source

Yes, that is the whole point of class inheritance.

You do not instantiate two objects: you create an instance of one object and run both the AClass constructor and BClass . The AClass constructor AClass responsible for initializing parts inherited from AClass , and the BClass constructor BClass responsible for initializing additional things defined in BClass .

+2
source

Yes.

The BClass constructor is as follows:

 public BClass () { super (); // hidden line, added by compiler System.out.println("Constructor B"); } 

If you do not want to use the default constructor, you can do the following:

 public BClass () { super (parameters); // now you will use different constructor from AClass // compiler will not add here call to "super ()" System.out.println("Constructor B"); } 

From oracle site: If the constructor does not explicitly call the constructor of the superclass, the Java compiler automatically inserts a call to the constructor without arguments to the superclass. If the superclass does not have a constructor with no arguments, you will get a compile-time error. An object has such a constructor, so if Object is the only superclass, there is no problem.

+2
source

Source: https://habr.com/ru/post/906880/


All Articles