[英]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. 我想知道如何在JVM中处理这个问题,当控件在基类构造函数中时,子类的构造函数尚未被调用,因此Object尚未完全构造。
I understand the ill effects of calling overriden methods from base class constructor but just wish to understand as how this is made possible. 我理解从基类构造函数调用override方法的不良影响,但只是希望了解如何使其成为可能。
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 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 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 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... someMethod在Sub类中执行...
Sub constructor is executing... 子构造函数正在执行...
Does object in java created before Constructor is invoked ? 是否在调用Constructor之前创建了java中的对象?
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. 构造函数的内部名称是<init>
,它的返回类型总是为void
这意味着它不返回对象,只是初始化它。
Note: Unsafe.allocateInstance
will create an object without calling a constructor and is useful for de-serialization. 注意: Unsafe.allocateInstance
将在不调用构造函数的情况下创建对象,并且对反序列化很有用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.