Is an object created in java before the constructor is created?

When overridden methods are called from the constructor of the base class, the method defined in the subclass is also called in accordance with the concept of run-time polymorphism. I wonder how this will be taken care of in the JVM when the control is in the constructor of the base class, the constructor of the subclass has not yet been called, and therefore the object is not yet completely constructed.

I read and also understood the harmful effects of such calls on overridden methods from base class constructors, but I just want to understand how this became possible. I feel like the object on the heap is created before the constructor is called, and when the constructor is called, the properties are initialized. Please provide your valuable data for the above.

Below is a code demonstrating the same thing.

Base.java

public class Base {
    public Base() {
            System.out.println("Base constructor is executing...");
            someMethod();
    }

    public void someMethod() {
            System.out.println("someMethod defined in Base class executing...");
    }
}

Sub.java

public class Sub extends Base{
    public Sub() {
            System.out.println("Sub constructor is executing...");
    }
    @Override
    public void someMethod() {
            System.out.println("someMethod defined in Sub class executing...");
    }
}

Client.java

public class Client {
    public static void main(String[] args) {
            Sub obj = new Sub();
    }
}

Console output

The base constructor is running ...

someMethod defined in the execution of the Sub ... class

The auxiliary constructor is running ...

+4
source share
1 answer

Is an object created in java created before the constructor is called?

Yes, otherwise you will not have an object to initialize.

At the byte code level, an object is first created, and then a constructor is called that runs in the object for initialization. The internal name for the constructor <init>, and the return type always voidmeans that it does not return an object, only initializes it.

: Unsafe.allocateInstance -.

+5

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


All Articles