gpt4 book ai didi

java - 子类的对象创建是否创建父类(super class)的对象,如果是,是否可以在子类中访问它?

转载 作者:搜寻专家 更新时间:2023-10-31 19:44:47 26 4
gpt4 key购买 nike

我的问题是我们是否可以在实例化子类时访问和使用间接/隐式创建的父类(super class)对象。

假设 ClassASubClassofA 的父类(super class),我们在客户端类 ClientClass 中实例化 SubClassofA 使用 SubClassofA object = new SubClassofA();

由于当我们创建子类对象时整个继承层次结构被实例化,我想知道,是否可以在客户端类中访问类 ClassA 的对象?

如果不可能,可能是什么原因?如果我们可以访问父类(super class)对象而无需重新创建父类(super class)对象,是否会节省大量堆内存?

我可能误解了构造函数链和继承层次结构的整个概念,但请让我知道您对此的看法。

public class ClassA {}

public class SubClassofA extends ClassA {}

public class ClientClass {

public static void main(String[] args) {
// TODO Auto-generated method stub

SubClassofA object = new SubClassofA();

//Above construct means that an instance of super class ClassA exists too
// If we can use those super class instances directly, will it result in memeory saving?
//is it even possible to access implicitly created super class objects tied to subclass?


}
}

最佳答案

Since whole inheritance hierarchy gets instantiated when we create a subclass objects, I was wondering, is it possible to access object of class ClassA in client class?

这是很多人都感到困惑的事情。如果您创建子类的对象,那并不意味着它创建父类(super class)的对象。

它只是调用父类(super class)的构造函数,只是为了确保在父类(super class)中初始化所有必需的字段,但这不会创建父类(super class)的对象 .

This question会帮助你理解这个概念。

Check Kevin's answer:

It doesn't create two objects, only one: B.

When inheriting from another class, you must call super() in your constructor. If you don't, the compiler will insert that call for you as you can plainly see.

The superclass constructors are called because otherwise the object would be left in an uninitialized state, possibly unbeknownst to the developer of the subclass.

关于java - 子类的对象创建是否创建父类(super class)的对象,如果是,是否可以在子类中访问它?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34349164/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com