我该如何访问父类作用域内,但类作用域外的变量?(问题标题)

3

我有一道考试题,问我是否可以访问变量x,其中包含值1?解决方案是我可以,但我想知道具体是如何做到的?

class A {
    int x = 1; //this is what I need access to.
    class B {
        int x = 2;
        void func(int x) {...}
    }
}

2
为什么现在的考试总是集中在边缘情况上,而这些情况通常表明了糟糕的实践呢? - Bathsheba
3个回答

3
class A {
    int x = 1;

    class B {
        int x = 2;

        void func(int x) {
            System.out.println(A.this.x);
        }
    }
}

使用示例:

public class Main {
    public static void main(String[] args) {        
        A a = new A();
        A.B b = a.new B();

        b.func(0); // Out is 1
    }
}

1
要访问父实例,您可以使用this关键字,如ParentClassName.this 子类不能是静态的。

1

是的,您可以访问值为1的变量x。

这里A是您的外部类,B是非静态内部类。

要访问外部类A的变量x,您可以像这样做

class B {
    int x = 2;
    void func(int x) {
      System.out.print(A.this.x +"  and  "+x);
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接