java - 访问父类(super class)的私有(private)成员

标签 java oop inheritance

从子类间接访问父类(super class)私有(private)成员的例子是什么?

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.

引自 http://docs.oracle.com/javase/tutorial/java/IandI/subclasses.html

最佳答案

在引用中,我们谈论“嵌套”类

这是一个内部类如何访问外部类的私有(private)字段的示例。

class OuterClass {
private int x = 7;

public void makeInner(){
    InnerClass in = new InnerClass();
    in.seeOuter();
}
class InnerClass {
    public void seeOuter() {
        System.out.println("Outer x is " + x);
    }
}
public static void main(String[] args) {
    OuterClass.InnerClass inner = new OuterClass().new InnerClass();
    inner.seeOuter();
}

最后,如果你用 InnerClass 扩展一个类,如果你的 InnerClass 是公共(public)的或 protected ,他们也将访问 OuterClass 的私有(private)字段

关于java - 访问父类(super class)的私有(private)成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14521324/

相关文章:

java - 将数据从 Jtable 传递到 Ireport

java - 堆栈实现 java - LinkedList vs Vector

Python:强制新型类

javascript - JavaScript 中的原型(prototype)与函数式 OOP

java - 传递对象或对象属性

flutter - 如何为子类属性提供与 Dart 中的父类(super class)不同的类型?

java - 输出是什么?

下载大数据时 HttpServer 上的 java.lang.OutOfMemoryError

java - ListCell 不显示在 ListView 上

c++ - 将虚函数覆盖为非虚函数可以吗?