gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:42:04 25 4
gpt4 key购买 nike

它是用 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com