私有字段是否由子类继承? [英] Are private fields inherited by the subclass?
问题描述
我已经读过子类不能继承私有字段或方法。但是,在此示例中
I have read that a subclass cannot inherit private fields or methods. However, in this example
class SuperClass {
private int n=3;
int getN() {
return n;
}
}
class SubClass extends SuperClass {
public static void main(String[] args) {
SubClass e = new SubClass();
System.out.println("n= " + e.getN());
}
}
当我运行 main
我得到的输出为 n = 3
。似乎 SubClass
从 SuperClass
n >。
When I run main
I get the output as n=3
. Which seems that SubClass
is inheriting the private attribute n
from SuperClass
.
所以,请解释这里发生了什么。谢谢。
So, please explain what's going on here. Thank you.
推荐答案
子类'有'其超类的字段,但无法直接访问它们。类似地,子类'拥有'私有方法,但你不能直接从子类调用或覆盖它们。
The subclass 'has' the fields of its superclass, but does not have access to them directly. Similarly, the subclass 'has' the private methods, but you cannot call or override them from the subclass directly.
在关于继承的Java文档,它说
子类不继承其父类的私有成员。
A subclass does not inherit the private members of its parent class.
但是,我觉得将它想象为更有用
However, I find it more useful to think of it as
子类继承其父类的私有成员但无权访问他们
A subclass inherits the private members of its parent class but does not have access to them
但这归结为sematics。
but this boils down to sematics.
这篇关于私有字段是否由子类继承?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!