我有一個考試例子,詢問我是否可以訪問包含值1的x變量?解決辦法是我可以,但我很感興趣,究竟是如何?如何訪問類作用域之外但父類作用域內的變量?
class A {
int x = 1; //this is what I need access to.
class B {
int x = 2;
void func(int x) {...}
}
}
我有一個考試例子,詢問我是否可以訪問包含值1的x變量?解決辦法是我可以,但我很感興趣,究竟是如何?如何訪問類作用域之外但父類作用域內的變量?
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
子類必須不能是靜態
是的,你可以用va訪問變量x lue 1.
這裏A是你的外部類,B是非靜態內部類。
要訪問外部類A的變量x,你可以做這樣的事情
class B {
int x = 2;
void func(int x) {
System.out.print(A.this.x +" and "+x);
}
}
爲什麼考試這幾天一直專注於邊緣案件常反映不良做法的? – Bathsheba