我有一道考试题,问我是否可以访问变量x,其中包含值1?解决方案是我可以,但我想知道具体是如何做到的?
class A {
int x = 1; //this is what I need access to.
class B {
int x = 2;
void func(int x) {...}
}
}
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
}
}
ParentClassName.this
子类不能是静态的。是的,您可以访问值为1的变量x。
这里A是您的外部类,B是非静态内部类。
要访问外部类A的变量x,您可以像这样做
class B {
int x = 2;
void func(int x) {
System.out.print(A.this.x +" and "+x);
}
}