[英]Call an instance variable when its name is same with the argument variable
我有這個代碼:
class Foo {
int x = 12;
public static void go(final int x) {
System.out.println(x);
}
}
參數final x和實例x具有相同的名稱。 如果我想在go()方法中使用它,我將如何引用實例變量x = 12,因為它的名稱與參數變量相同?
您需要將其設置為靜態才能在靜態方法中使用它:
static int x = 12;
然后你可以通過類名獲得它的引用:
public static void go(final int x)
{
System.out.println(Foo.x);
}
或者,創建一個實例並在本地使用它:
int x = 12;
public static void go(final int x)
{
Foo f = new Foo();
System.out.println(f.x);
}
或者使用實例方法,並使用關鍵字this
引用實例x
:
int x = 12;
public void go(final int x)
{
System.out.println(this.x);
}
this.x
指向實例變量。
為了引用一個實例變量,你必須在一個真實的實例中:你的方法不應該是static
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.