当一个变量初始化无论是在本地范围内以及全球范围内,我们如何利用全球范围内不使用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
}
}
Also See :
如果不使用this
它将始终是局部变量。
It is impossible without this. The phenomenon is called variable hiding .
If you are scoping the variable reference with this
it will always point to the instance variable.
If a method declares a local variable that has the same name as a class-level variable, the former will 'shadow' the latter. To access the class-level variable from inside the method body, use the this keyword.
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;
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.