[英]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.