[英]Java variable scope
當一個變量初始化無論是在本地范圍內以及全球范圍內,我們如何利用全球范圍內不使用this
在同級別的關鍵字?
class MyClass{
int i;//1
public void myMethod(){
i = 10;//referring to 1
}
public void myMethod(int i){//2
i = 10;//referring to 2
this.i = 10 //refering to 1
}
}
另請參閱:
如果不使用this
它將始終是局部變量。
沒有這個是不可能的。 這種現象稱為變量隱藏 。
如果您要在this
范圍內定義變量引用,它將始終指向實例變量。
如果方法聲明的局部變量與類級變量的名稱相同,則前者將“遮蓋”后者。 要從方法主體內部訪問類級變量,請使用this關鍵字。
public class VariableScope {
int i=12;// Global
public VariableScope(int i){// local
System.out.println("local :"+i);
System.out.println("Global :"+getGlobal());
}
public int getGlobal(){
return i;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.