这是面试问题。
子类继承private吗 字段?
我的回答是“不”,因为我们不能使用“正常的面向对象的方式”访问它们。但是采访者认为它们是继承的,因为我们可以间接或使用反射访问这些字段,并且它们仍然存在于对象中。
回来后,我在javadoc中找到了以下引用:
超类中的私人成员 一个 子类不继承私有 父类的成员。
你知道面试官观点的论据吗?
这是面试问题。
子类继承private吗 字段?
我的回答是“不”,因为我们不能使用“正常的面向对象的方式”访问它们。但是采访者认为它们是继承的,因为我们可以间接或使用反射访问这些字段,并且它们仍然存在于对象中。
回来后,我在javadoc中找到了以下引用:
超类中的私人成员 一个 子类不继承私有 父类的成员。
你知道面试官观点的论据吗?
当前回答
子类不继承父类的私有成员。但是,如果父类具有用于访问其私有字段的公共或受保护方法,则子类也可以使用这些方法
参考: https://docs.oracle.com/javase/tutorial/java/IandI/subclasses.html: ~:文本=私人% 20成员在% 20 % % 20 20超类,由% % 20使用% 20 20 % 20子类。
其他回答
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(重点是我的)和行为。”
私有字段即使不能被子类访问,也是父类的继承状态。
这里的问题/答案中的大多数困惑都围绕着继承的定义。
显然,正如@DigitalRoss解释的那样,子类的OBJECT必须包含其父类的私有字段。正如他所说,无法访问私人会员并不意味着它不存在。
然而。这与类继承的概念不同。在java世界中,存在语义问题时,仲裁人是java语言规范(目前是第3版)。
正如JLS所述(https://docs.oracle.com/javase/specs/jls/se8/html/jls-8.html#jls-8.2):
已声明的类的成员 Private不被继承 该类的子类。只有成员 声明为受保护的类的 或public由子类继承 类以外的包中声明 声明类的语句。
这就解决了采访者提出的问题:“子类继承私有字段吗?”(我强调了一下)
答案是否定的。他们没有。子类的对象包含父类的私有字段。子类本身没有父类的私有字段的概念。
这是学究性质的语义学吗?是的。这是个有用的面试问题吗?可能不会。但是JLS为Java世界建立了定义,并且这样做(在本例中)是明确的。
编辑(删除了Bjarne Stroustrup的平行引用,由于java和c++之间的差异,这可能只会增加混淆。我将让我的答案取决于JLS:)
例如,
class Person {
private String name;
public String getName () {
return this.name;
}
Person(String name) {
this.name = name;
}
}
public class Student extends Person {
Student(String name) {
super(name);
}
public String getStudentName() {
return this.getName(); // works
// "return this.name;" doesn't work, and the error is "The field Person.name is not visible"
}
}
public class Main {
public static void main(String[] args) {
Student s = new Student("Bill");
String name = s.getName(); // works
// "String name = s.name;" doesn't work, and the error is "The field Person.name is not visible"
System.out.println(name);
}
}
子类不继承父类的私有成员。但是,如果父类具有用于访问其私有字段的公共或受保护方法,则子类也可以使用这些方法
参考: https://docs.oracle.com/javase/tutorial/java/IandI/subclasses.html: ~:文本=私人% 20成员在% 20 % % 20 20超类,由% % 20使用% 20 20 % 20子类。
我们可以简单地声明,当父类被继承时,父类的私有成员实际上成为子类的私有成员,并且不能被进一步继承或子类的对象不可访问。