内部类可见性有些麻烦

问题描述 投票:1回答:4

我正面临java内部类,我在外部变量可见性方面遇到了一些麻烦。

class A {
    private int x = 5;
    class B extends A{
        public void fun(B b){
            b.x = 10; //here
        }
    }
}

如果内部和外部类之间没有可见性限制,为什么我不能做这样的事情(参见“here”标签)?我真的不理解这些规则。

java subclass inner-classes
4个回答
2
投票

在你的例子中,成员变量x不是B类的属性,所以b.x = 10没有sesne,因此错误,它与可见性规则无关。尝试x = 10工作正常,这是A.this.x = 10super.x = 10的捷径。


1
投票

无法在子类中访问修饰符private

class A {
    private int x = 5; // The issue is in `private` in this line
    class B extends A{
        public void fun(B b){
            b.x = 10; //here
        }
    }
}

如果删除修饰符private并将其更改为defaultpublicprotected,您将能够访问该变量。

请通过link以便更好地理解。

更新:

删除extends关键字(现在B类不是子类,只是内部类),只有使用这个OR super关键字才能访问变量x。用法在link详细说明


0
投票

你需要知道这三个privateprotecteddefaultpublicaccess说明符

  1. private变量只能在自身类中修改。不包括subclass
  2. default变量可以在同一个包中修改。
  3. protected变量可以在子类中以及在相同的包和它自身中进行修改
  4. public变量可以在任何地方修改。

你可以在这个link上看到这个

如果你使用这个例子,这可以使用superspecifiers修改你的变量来访问你的可见

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而不是成员变量或超类变量。


0
投票

这个很特别。内部类可以访问外部类的私有字段。这可以用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
}
© www.soinside.com 2019 - 2024. All rights reserved.