有人告诉我,对于 Java 子类,它可以继承其父类(super class)的所有成员。那么这是否意味着私有(private)成员(member)呢?我知道它可以继承 protected 成员。
谁能给我解释一下。我现在完全糊涂了。
最佳答案
不,私有(private)成员不继承,因为私有(private)成员的范围仅限于定义它的类.只有 public 和 protected 成员被继承。
Private Members in a Superclass
A subclass does not inherit the private members of its parent class. However, if the superclass has public or protected methods for accessing its private fields, these can also be used by the subclass. A nested class has access to all the private members of its enclosing class—both fields and methods. Therefore, a public or protected nested class inherited by a subclass has indirect access to all of the private members of the superclass.
来自JLS
,
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.
关于java - Java继承中的私有(private)成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6543328/