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

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

问题描述

当我们在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天全站免登陆