“在子类的实例化过程中,超类的私有字段是否也在堆内存中占有一席之地? [英] "Are private fields of superclass getting a place inside heap memory too, during instantiation of subclass?

查看:38
本文介绍了“在子类的实例化过程中,超类的私有字段是否也在堆内存中占有一席之地?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑一个超类 A 和一个派生类 B,而 A 包含一个私有变量 x.B 包含一个显式的 super() 调用作为其构造函数中的第一个参数,而 B 可能还有一些其他变量,如 yz.据我所知,私有字段没有继承.这是否意味着私有字段在执行时不会被实例化:

Consider a Superclass A and a derived class B whereas A contains a private variable x. B contains an explicit super() call as first argument inside its constructor while there might be some other variables of B like y and z. As far as I know there is no inheritance for private fields. Does that mean private fields will not get instantiated while executing:

B b = new b(); 

我的问题是:运行上面的代码后堆是什么样子的?当然会有yz,但是在这种情况下x呢?

My question is: How does the heap look like after running the above code? Of course there will be y and z, but what about x in this case?

推荐答案

Field inheritance 和 field visibility 是两个独立的概念,不要混淆.

Field inheritance and field visibility are two separate concepts, not to be confused.

在某种程度上(为了简化一点),类是创建对象的模板.因此,如果一个类 A 声明了两个字段 f1f2,那么实例化 A 会创建对象(并为它们在堆上)具有这两个字段.

In a way (to simplify a bit), a class is a template from making objects. So if a class A declares two fields f1 and f2, then instantiating A creates objects (and allocates memory for them on the heap) that have these two fields.

子类也是创建对象的模板,但该模板表示为对另一个类的添加.因此,如果 B 类声明了字段 f3 并扩展了 A,它基本上是在说,获取 A 的所有字段定义,并添加f3".因此,实例化 B 会生成一个具有三个字段 f1f2f3 的对象.

A subclass is also a template for making objects, but this template is expressed as an addition to another class. So if class B declares field f3 and extends A, it's basically saying, "take all the fields that A defines, and add f3". So instantiating B results in an object with three fields f1, f2, f3.

字段可见性,如通过privatepublic 等访问修饰符表达的,是一种控制代码看到"(或可以引用)的部分的方法某个领域.private 修饰符意味着声明该字段的类之外的任何代码都不能引用该字段.然而,这并不意味着该领域不再存在.做一个狡猾的平行,如果你和另一个人在一个房间里,你关了灯,你看不到另一个人,但他们还在那里.

Field visibility, as expressed through access modifiers like private and public, is a way to control which part of the code "sees" (or can refer to) a certain field. The private modifier means that no code outside of the class that declares the field can refer to this field. However, it doesn't mean that the field stops existing. To make a dodgy parallel, if you and another person are in a room and you turn off the light, you can't see the other person, but they are still there.

为了强调概念是独立的这一点,请考虑在某些情况下您可以看到不是继承的字段(例如,因为它们是非私有的,但在不在同一类层次结构中的类中).在某些情况下,您看不到继承的字段,例如超类中的私有字段.

To emphasize the point that the concepts are separate, consider that in some cases you can see fields that are not inherited (e.g., because they are non-private, but in a class not in the same class hierarchy). And in some cases you can't see fields that are inherited, as in the case of private fields in the superclass.

这篇关于“在子类的实例化过程中,超类的私有字段是否也在堆内存中占有一席之地?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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