[英]Access protected field of inner class through inheritance
我正在嘗試o通過在另一個內部類中繼承來訪問內部類的受保護字段。 但是我遇到了一個問題:
package a;
class A{
public class Inner{
protected int i =5;
}
}
package b;
class B{
public class BInner extends A.Inner{
dsds
void test(){
System.out.println(i); // that's works fine, i
}
}
void print(){
System.out.println(new BInner().i) // but why i cant access this field from here? Compiler just says that there is protected access ...
}
}
有什么方法可以訪問該字段?
protected
訪問修飾符意味着該字段或方法僅對類本身及其子級可用。 由於類B
沒有擴展B.BInner
,因此它無法訪問B.BInner.i
。
使用訪問修飾符的最常見方法是使用getter / setter對 ,您可以在A.Inner
中A.Inner
進行聲明(因為這是聲明i
的地方,而B.BInner
將繼承這些方法):
class A{
public class Inner{
protected int i =5;
public int getI() {
return i;
}
public void setI(int i) {
this.i = i;
}
}
}
然后,在B.BInner
對象上調用getI()
將返回i
的值,並且由於它是public
,因此可以在任何地方使用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.