这是面试问题。

子类继承private吗 字段?

我的回答是“不”,因为我们不能使用“正常的面向对象的方式”访问它们。但是采访者认为它们是继承的,因为我们可以间接或使用反射访问这些字段,并且它们仍然存在于对象中。

回来后,我在javadoc中找到了以下引用:

超类中的私人成员 一个 子类不继承私有 父类的成员。

你知道面试官观点的论据吗?


当前回答

不,私有字段不被继承。唯一的原因是子类不能直接访问它们。

其他回答

Yes

重要的是要认识到,虽然有两个类,但只有一个对象。

当然,它继承了私有字段。它们大概是正确的对象功能所必需的,虽然父类的对象不是派生类的对象,但派生类的实例基本上肯定是父类的实例。如果没有所有的领域,就不可能是这样。

不,你不能直接访问它们。是的,它们是遗传的。他们必须如此。

这是个好问题!


更新:

呃,“不”

我想我们都学到了一些东西。由于JLS提出了确切的“不继承”措辞,所以回答“不继承”是正确的。由于子类不能访问或修改私有字段,因此,换句话说,它们不会被继承。但实际上只有一个对象,它确实包含私有字段,因此如果有人以错误的方式使用JLS和教程措辞,将很难理解OOP、Java对象以及实际发生的事情。

更新更新:

这里的争议涉及到一个根本的模糊:讨论的究竟是什么?的对象?或者我们在某种意义上谈论的是类本身?当描述类而不是对象时,允许有很大的自由度。因此,子类不继承私有字段,但作为子类实例的对象当然包含私有字段。

私有类成员或构造函数只能在顶层类的主体(§7.6)中访问,该主体包含了成员或构造函数的声明。它不是由子类继承的。https://docs.oracle.com/javase/specs/jls/se7/html/jls-6.html#jls-6.6

不,私有字段不被继承。唯一的原因是子类不能直接访问它们。

It would seem that a subclass does inherit the private fields in that these very fields are utilized in the inner workings of the subclass (philosophically speaking). A subclass, in its constructor, calls the superclass constructor. The superclass private fields are obviously inherited by the subclass calling the superclass constructor if the superclass constructor has initialized these fields in its constructor. That's just an example. But of course without accessor methods the subclass cannot access the superclass private fields (it's like not being able to pop the back panel of an iPhone to take the battery out to reset the phone... but the battery is still there).

PS 我遇到的关于继承的许多定义之一是: “继承——一种编程技术,允许派生类扩展基类的功能,继承其所有的STATE(重点是我的)和行为。”

私有字段即使不能被子类访问,也是父类的继承状态。

这取决于你对“继承”的定义。子类在内存中仍然有字段吗?肯定。它能直接访问它们吗?不。这只是定义的微妙之处;关键是要理解到底发生了什么。