7

この記事を読んでいたとき、セクションPrivate Members in a Superclassの下に、この行を見ました

ネストされたクラスは、それを囲むクラスのすべてのプライベート メンバー (フィールドとメソッドの両方) にアクセスできます。したがって、サブクラスによって継承されたパブリックまたは保護されたネストされたクラスは、スーパークラスのすべてのプライベート メンバーに間接的にアクセスできます。

私の質問は、 inのNestedクラスに直接アクセスするにはどうすればよいですか(任意の ,フィールドにアクセスできるように)?BaseDerivedpublicprotected

方法があれば、スルーのプライベート フィールドにどのようにDerivedアクセスできますか?pBaseNested

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' ?
    }

}

このスレッドに時間と労力を割いていただき、ありがとうございます。

4

3 に答える 3

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

または、派生クラスの場合、これは機能するはずです:

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

super キーワードを使用する必要があるかどうかはわかりません

于 2013-07-17T18:06:14.897 に答える