子类是否继承私有字段? [英] Do subclasses inherit private fields?

查看:26
本文介绍了子类是否继承私有字段?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一道面试题.

子类是否继承私有字段?

Does subclasses inherit private fields?

我回答否",因为我们无法使用正常的 OOP 方式"访问它们.但是面试官认为它们是继承的,因为我们可以间接或使用反射访问这些字段,并且它们仍然存在于对象中.

I answered "No", because we can't access them using the "normal OOP way". But the interviewer thinks that they are inherited, because we can access such fields indirectly or using reflection and they still exist in the object.

回来后,我在javadoc:

超类中的私有成员

A子类不继承私有其父类的成员.

A subclass does not inherit the private members of its parent class.

你知道面试官的意见有什么论据吗?

Do you know any arguments for the interviewer's opinion?

推荐答案

此处问题/答案中的大部分混淆都围绕着继承的定义.

Most of the confusion in the question/answers here surrounds the definition of Inheritance.

显然,正如@DigitalRoss 解释的那样,子类的 OBJECT 必须包含其超类的私有字段.正如他所说,无法访问私人成员并不意味着它不存在.

Obviously, as @DigitalRoss explains an OBJECT of a subclass must contain its superclass's private fields. As he states, having no access to a private member doesn't mean its not there.

不过.这与类的继承概念不同.与 Java 世界的情况一样,存在语义问题的仲裁者是 Java 语言规范(目前为第 3 版).

However. This is different than the notion of inheritance for a class. As is the case in the java world, where there is a question of semantics the arbiter is the Java Language Specification (currently 3rd edition).

正如 JLS 所述(https://docs.oracle.com/javase/specs/jls/se8/html/jls-8.html#jls-8.2):

As the JLS states (https://docs.oracle.com/javase/specs/jls/se8/html/jls-8.html#jls-8.2):

声明的类的成员私有不被继承该类的子类.仅限会员声明为受保护的类的或 public 由子类继承在包中声明,而不是其中声明了类.

Members of a class that are declared private are not inherited by subclasses of that class. Only members of a class that are declared protected or public are inherited by subclasses declared in a package other than the one in which the class is declared.

这解决了面试官提出的确切问题:do subCLASSES继承私有字段".(重点是我加的)

This addresses the exact question posed by the interviewer: "do subCLASSES inherit private fields". (emphasis added by me)

答案是否定的.他们没有.子类的对象包含其超类的私有字段.子类本身没有其超类的私有字段的概念.

The answer is No. They do not. OBJECTS of subclasses contain private fields of their superclasses. The subclass itself has NO NOTION of private fields of its superclass.

这是学究式的语义吗?是的.这是一个有用的面试问题吗?可能不是.但是 JLS 为 Java 世界建立了定义,并且(在本例中)明确地这样做了.

Is it semantics of a pedantic nature? Yes. Is it a useful interview question? Probably not. But the JLS establishes the definition for the Java world, and it does so (in this case) unambiguously.

已编辑(删除了 Bjarne Stroustrup 的平行引用,由于 java 和 c++ 之间的差异可能只会增加混乱.我会让我的答案取决于 JLS :)

EDITED (removed a parallel quote from Bjarne Stroustrup which due to the differences between java and c++ probably only add to the confusion. I'll let my answer rest on the JLS :)

这篇关于子类是否继承私有字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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