Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does object in java created on heap before Constructor is invoked?

When overridden methods are called from the Constructor of the base class then also as per the run time polymorphism concept the method defined in the sub class gets invoked. I wonder as how this is taken care of in the JVM, when control is in the base class constructor the constructor of the sub class is yet to be called and hence Object is not yet completely constructed.

I understand the ill effects of calling overriden methods from base class constructor but just wish to understand as how this is made possible.

I feel object in the heap is created before constructor is invoked and as constructor is invoked the properties are initialized. Please provide your valuable inputs for the above.

Below is the code demonstrating the same.

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();
    }
}

Output on console is

Base constructor is executing...

someMethod defined in Sub class executing...

Sub constructor is executing...

like image 986
nits.kk Avatar asked Feb 15 '16 12:02

nits.kk


1 Answers

Does object in java created before Constructor is invoked ?

Yes, otherwise you would not have an object to initialise.

At the byte code level, the object is created first, and then the constructor is called, passing in the object to initialise. The internal name for a constructor is <init> and it's return type is always void meaning it doesn't return the object, only initialise it.

Note: Unsafe.allocateInstance will create an object without calling a constructor and is useful for de-serialization.

like image 149
Peter Lawrey Avatar answered Nov 15 '22 00:11

Peter Lawrey