[英]Java nested class visibility rules
在下面訪問other
對象的字段n
是否有較簡單的方法?
public class NestedVisibility
{
private int n = 42;
public static class B extends NestedVisibility {
public void foo(NestedVisibility guest) {
super.n = 0; // OK
guest.n = 0; // OK
B other = new B();
other.n = 0; // Compile-time error. Weird!
((NestedVisibility)other).n = 0; // OK
}
}
}
我必須做更多的工作來訪問除guest
的私有字段以外的other
私有字段,這很奇怪嗎?
私有變量不被擴展類繼承。 您可以通過父類繼承的getter和setter來訪問它們。
這是您的代碼,其重寫如下:
public class NestedVisibility
{
private int n = 42;
public int getN(){
return this.n;
}
public void setN(int n){
this.n = n;
}
public static class B extends NestedVisibility {
public void foo(NestedVisibility guest) {
super.n = 0; // OK
guest.n = 0; // OK
B other = new B();
other.setN(0);
console.log(other.getN());
}
}
}
因此,基本上class B
沒有field n
但它具有super field n
。 這篇文章有很多關於此的信息,此外,互聯網上也有很多關於它的隨機博客。
但是,您可以從嵌套類訪問私有變量。 NestedVisibility
,如果您創建一個類型為NestedVisibility
(不擴展)的對象,則可以在嵌套類中直接訪問它,如下所示:
public class NestedVisibility
{
private int n = 42;
public static class B extends NestedVisibility {
public void foo(NestedVisibility guest) {
super.n = 0; // OK
guest.n = 0; // OK
NestedVisibility other = new NestedVisibility();
other.n = 0; //OK
}
}
}
希望這有助於清理問題。
私有作用域變量僅對它們所屬的類可見。
如果您希望擴展該類並希望授予對該類變量的訪問權限,則應使用受保護的范圍聲明它。
public class NestedVisibility
{
protected int n = 42;
public static class B extends NestedVisibility {
public void foo(NestedVisibility guest) {
super.n = 0; // OK
guest.n = 0; // OK
B other = new B();
other.n = 0; // now is OK
((NestedVisibility)other).n = 0; // OK
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.