我正面临java内部类,我在外部变量可见性方面遇到了一些麻烦。
class A {
private int x = 5;
class B extends A{
public void fun(B b){
b.x = 10; //here
}
}
}
如果内部和外部类之间没有可见性限制,为什么我不能做这样的事情(参见“here”标签)?我真的不理解这些规则。
在你的例子中,成员变量x
不是B类的属性,所以b.x = 10
没有sesne,因此错误,它与可见性规则无关。尝试x = 10
工作正常,这是A.this.x = 10
或super.x = 10
的捷径。
你需要知道这三个private
,protected
,default
,public
access说明符
private
变量只能在自身类中修改。不包括subclass
default
变量可以在同一个包中修改。protected
变量可以在子类中以及在相同的包和它自身中进行修改public
变量可以在任何地方修改。你可以在这个link上看到这个
如果你使用这个例子,这可以使用super
specifiers修改你的变量来访问你的可见
class A {
private int x = 5;
class B extends A{
public void fun(B b){
b.x = 10; //here error
super.x=1;//this is ok
}
}
}
这个b.x = 10; //here error
这个问题是b是一个方法的parm而不是成员变量或超类变量。
这个很特别。内部类可以访问外部类的私有字段。这可以用fun(A)
方法显示
class A {
private int x = 5;
class B extends A{
public void fun(A a){
a.x = 5; //Valid since we are in the same class (inner-class can access private field)
}
}
现在,如果你有一个B
参数,这有点不同,因为它会尝试使用继承而不是外部内部链接:
public void fun(B b){
b.x = 10; //Access using inheritence, not OK for private field
((A)b).x = 10; //Casting into A to be able to access the private field (just like fun(A).
}
请注意,这是一个问题,因为您更新参数receive in参数,您可以轻松更新当前内部实例
public void fun(){
x = 10; //OK : access to A.x from inner class
super.x = 10; //OK : same
this.x = 10; // KO : trying to access a private variable from B scope
}