当我们实例化一个对象时,是否创建一个超类的实例? [英] Does an instance of superclass get created when we instantiate an object?

查看:272
本文介绍了当我们实例化一个对象时,是否创建一个超类的实例?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我们在java中实例化一个特定的类时,会创建一个超类的实例。如果是这种情况,那么将会有很多实例化所有超类的开销。我试过下面的代码:

Does an instance of superclass get created when we instantiate a particular class in java. If that is the case then there would be a lot of overhead of instantiating all the super classes. I tried 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();
    }
}

代码的输出是:

Constructor A

Constructor B

那么,这是否意味着当我们实例化一个类时,超类的对象的完整层次结构是如何创建的?

So, does it mean that the complete hierarchy of the objects of the superclasses get created when we instantiate a class?

推荐答案

创建单个对象 - 但是该对象是超类和子类的实例(和 java.lang.Object 本身)。没有三个单独的对象。有一个对象具有一组字段(基本上是在层次结构上下声明的所有字段的并集)和一个对象头。

A single object is created - but that object is an instance of both the superclass and the subclass (and java.lang.Object itself). There aren't three separate objects. There's one object with one set of fields (basically the union of all the fields declared up and down the hierarchy) and one object header.

构造函数在继承层次结构中执行,但是 this 引用对于所有这些构造函数都是相同的;它们都有助于单个对象的初始化。

The constructors are executed all the way up the inheritance hierarchy - but the this reference will be the same for all of those constructors; they're all contributing to the initialization of the single object.

这篇关于当我们实例化一个对象时,是否创建一个超类的实例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆