java - Java继承中的私有(private)成员

标签 java inheritance subclass superclass private-members

有人告诉我,对于 Java 子类,它可以继承其父类(super class)的所有成员。那么这是否意味着私有(private)成员(member)呢?我知道它可以继承 protected 成员。

谁能给我解释一下。我现在完全糊涂了。

最佳答案

不,私有(private)成员不继承,因为私有(private)成员的范围仅限于定义它的类.只有 public 和 protected 成员被继承。

来自Java Documentation ,

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.

一个有用的链接:Does subclasses inherit private fields?

关于java - Java继承中的私有(private)成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6543328/

相关文章:

java - JPA 单个外键 ID 引用两个(或更多)表

java - 如何基于EntityMentionsAnnotator进行维基化/实体链接?

Java 使用包私有(private)构造函数继承公共(public)类

java - Hibernate:如何将子类链接到其父类(super class)?

swift - 以编程方式访问 UIViewController 子类中 UIView 子类的成员

java - neo4j: java 错误: 找不到 NodeImpl#0 的属性

java - 传递和返回 StringBuilder : Java

c++ - 为什么要使用 "using"关键字来访问我的基类方法?

java - 有没有什么技巧可以在运行时知道实例泛型的实际具体类?

json - 使用 ObjectMapper 的不同类型 JSON 文件