11

これは、同じ質問の少し詳細なバージョンです。

サブクラスが別のパッケージにあるサブクラスでは、(スーパークラスの) 保護された変数にアクセスできません。スーパークラスの継承された変数にのみアクセスできます。しかし、修飾子を「Protected static」に変更すると、スーパークラスの変数にもアクセスできます。なぜそうなのか。

これは、私が説明しようとしていた同じコードスニペットです。

package firstOne;

public class First {
    **protected** int a=7;
}

package secondOne;

import firstOne.*;

public class Second extends First {
    protected int a=10; // Here i am overriding the protected instance variable

    public static void main (String [] args){
        Second SecondObj = new Second();
        SecondObj.testit();
    }
    public void testit(){
        System.out.println("value of A in Second class is " + a);
        First b = new First();
        System.out.println("value in the First class" + b.a ); // Here compiler throws an error.
    }
}

上記の動作は予期されたものです。しかし、私の質問は、スーパークラスのインスタンス変数 'a' のアクセス修飾子を 'protected static' に変更すると、変数 (スーパークラスの変数) にもアクセスできるということです..! つまり、

package firstOne;

public class First {
    **protected static** int a=7;
}

package secondOne;

import firstOne.*;

public class Second extends First {
    protected int a=10;

    public static void main (String [] args){
        System.out.println("value in the super class" + First.a ); //Here the protected variable of the super class can be accessed..! My question is how and why..?
        Second secondObj = new Second();
        secondObj.testit();
    }

    public void testit(){
        System.out.println("value of a in Second class is " + a);
    }

}

上記のコードは、出力を示しています。

スーパークラス7の値

test1 クラスの x の値は 10 です

これはどのように可能ですか...?

4

2 に答える 2

0

オーバーライドはメソッドにのみ適用され、クラス変数には適用されません。変数をオーバーライドするようなものはありません。スーパークラスの変数 a にアクセスするシンボルをシャドーイングしています。

于 2015-10-20T09:07:39.287 に答える