gpt4 book ai didi

java - 将嵌套类继承到子类

转载 作者:搜寻专家 更新时间:2023-10-31 20:12:40 25 4
gpt4 key购买 nike

当我浏览 this 时文章,在 Private Members in a Superclass 部分下,我看到了这一行

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.

我的问题是我们如何直接访问 DerivedBaseNested 类(就像我们可以访问任何 public, protected 字段)?

如果有办法,Derived如何通过Nested访问Base的私有(private)字段p

public class Base {

protected int f;
private int p;

public class Nested {

public int getP() {
return p;
}
}
}

class Derived extends Base {

public void newMethod() {
System.out.println(f); // i understand inheriting protected field

// how to access the inherited Nested class here? and if accessed how to retrieve 'p' ?
}

}

在此先感谢您为此主题付出的时间和精力!

最佳答案

Base.Nested theClassBro= new Base.Nested();

或者对于派生类,这应该有效:

Derived.Nested theClassBro= new Derived.Nested();

我不确定你是否需要使用 super 关键字

关于java - 将嵌套类继承到子类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17706978/

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