![](/img/trans.png)
[英]Why can't my subclass access a protected variable of its superclass, when it's in a different package?
[英]How can ‘protected static’ variable of superclass be accessed in the subclass, where subclass resides in different package..?
這是同一個問題的略微詳細版本。
我們無法訪問子類中受保護的變量(超類),其中子類位於不同的包中。我們只能訪問supeclass的繼承變量。 但是如果我們將修飾符更改為'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
這怎么可能...?
從“檢查Java虛擬機中受保護成員的訪問權限”:
設m是屬於包p的類c中聲明的成員。 如果m是public,則可以通過(code in)任何類訪問它。 如果m是私有的,則只能通過c訪問。 如果m具有默認訪問權限,則只能由屬於p的任何類訪問它。
如果m受到保護,事情會稍微復雜一些。 首先, m可以被屬於p的任何類訪問,就像它具有默認訪問權一樣。 此外,它可以被C屬於與p不同的封裝的任何亞類s中被訪問,但有下列限制:·如果m不是靜態的,則類ø其成員正在被訪問必須是S或A的對象的S的子類中,書面ö≤ 秒 (如果m是靜態的,則限制不適: 米可被S總是訪問)。
我在JLS第6.6.2.1節中找到了引用,它支持關於“正在訪問其成員的對象必須是s或子類......”的部分。 我沒有看到任何支持靜態子句的東西,但根據你自己的例子,它顯然是正確的。
覆蓋僅適用於方法,而不適用於類變量。 沒有覆蓋變量的東西。 您正在隱藏訪問超類變量a的符號。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.