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

标签 java inheritance

我的问题是我们是否可以在实例化子类时访问和使用间接/隐式创建的父类(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/

相关文章:

java - Spring EasyMock 调用模拟方法时获取 null

inheritance - 我可以避免一个边缘是测试依赖的依赖循环吗?

java - Java 中的类型转换,技术信息

javascript - 通过继承 React.js 中的值来更改复选框的值

c++ - 如何通过基类指针调用派生类的虚函数

c# - 迷失在继承和多态中

java - 并发跳过列表?也就是说,不是 ConcurrentSkipListSet

java - 永久设置 DatePickerDialog 标题

java - 折线停止在我的 map 上绘制

java - SWT 中的米勒柱?