これは、同じ質問の少し詳細なバージョンです。
サブクラスが別のパッケージにあるサブクラスでは、(スーパークラスの) 保護された変数にアクセスできません。スーパークラスの継承された変数にのみアクセスできます。しかし、修飾子を「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 です
これはどのように可能ですか...?