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 ...
source
share