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

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

问题描述

这是一个面试问题。


子类是否继承私有
字段?

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

After I came back, I found the following quote in the javadoc:


超类中的私人成员

Private Members in a Superclass

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 ):


声明为
private的类的成员不会被该类的
子类继承。只有声明受保护的
或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 sub CLASSES 继承私有字段。 (重点是我添加)

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

答案是否定的。他们没有。子类的OBJECTS包含其超类的私有字段。子类本身没有其超类私有字段的NO OF。

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.

EDITED(删除了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天全站免登陆