gpt4 book ai didi

java - 公共(public)嵌套类的子类无法访问封闭类的私有(private)成员

转载 作者:行者123 更新时间:2023-12-01 18:04:31 26 4
gpt4 key购买 nike

我读过一句话here 像下面这样

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 super class.

现在我有如下代码

类储物柜{

private String Secret = "这是我的 secret ";

公共(public)类 Util { }

}

class StealSecret 扩展了 Locker.Util { }

但是我收到如下所示的编译时错误

No enclosing instance of type Locker is available due to some intermediate constructor invocation

我无法理解到底是什么导致了编译时错误。我在链接中读到的内容是错误的吗?

请举例说明如何通过扩展内部类来访问封闭类的私有(private)成员

最佳答案

其他答案已经解释了异常的原因,但没有解决

Please give me an example explaining the way to access the private members of enclosing class by extending the inner class

您的文档中的引用指出

A nested class has access to all the private members of its enclosing class—both fields and methods.

嵌套类是在另一个类中声明的类。 Locker.Util 是一个嵌套类。 StealSecret 不是(即使它确实编译了,请参阅下面的技巧来做到这一点)。

如果您确实需要扩展该内部类并且可以访问Locker类的private成员,您'还需要在 Locker 中声明子类

例如,

public class Locker {
private String secret = "This is my secret";

public class Util {
}

public class StealSecret extends Locker.Util {
public StealSecret() {
System.out.println(secret); // access
}
}
}
<小时/>

StealSecret 类扩展了一个内部类,它需要对该内部类的封闭类的实例的引用。您可以使用此技巧来提供该引用

class StealSecret extends Locker.Util {
public StealSecret(Locker enclosing) {
enclosing.super();
}
}

关于java - 公共(public)嵌套类的子类无法访问封闭类的私有(private)成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37776025/

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