java - 子类中的私有(private)字段在父类(super class)中是可访问的

标签 java jls

它是用 JLS 写的(见 8.3 节):

“子类可以访问父类(super class)的私有(private)字段——例如,如果 这两个类(class)都是同一类(class)的成员。然而,私有(private)领域永远不会 由子类继承。”

你能给出这个陈述的例子吗?

我知道我们可以这样写:

public class MyClass {
    private int x = 1;

    public void testExample(MyClass m) {
        m.x = 2;
    }
}

这里我们访问私有(private)字段 m.x 但我们没有“父类(super class)”-“子类”。

最佳答案

这是在谈论嵌套类——这是一个例子:

public class Test {
    public static void main(String[] args) {
        new Subclass(10).foo();
    }

    static class Superclass {
        private int x;

        Superclass(int x) {
            this.x = x;
        }
    }

    static class Subclass extends Superclass {
        Subclass(int x) {
            super(x);
        }

        public void foo() {
            Superclass y = this;
            System.out.println(y.x);
        }
    }
}

有效是因为 JLS 6.6 :

Otherwise, the member or constructor is declared private, and access is permitted if and only if it occurs within the body of the top level class (§7.6) that encloses the declaration of the member or constructor

这里 x 的使用是在 Test 的主体内,它是包含 x 声明的顶级类...虽然如果你尝试使用不合格的 x,或者只是 this.x,那会失败......正是因为 x 实际上不是 继承(根据您引用的规范)。

关于java - 子类中的私有(private)字段在父类(super class)中是可访问的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32273776/

相关文章:

java - 通过 Tibco JMS 发送可序列化对象会引发反序列化失败错误

java - 对于一个类的多个实例,Volatile 关键字无法按预期工作

java - 是否可以在不更改方法主体的情况下编译通用可变参数方法?

java - 使用 VPN ip 地址 htttp Urlconnection java

java - ASPxGridView java 的替代品?

java - 分包进口按需申报

Java 有界泛型 : Type inference bug?(方法调用,JLS 15.12.2.7)

java - 围绕 superfirst 工作

关于通配符的 Java 语言规范

java - JVM 尖括号中的标识符导致内部方法错误