Java variable scope

2020-02-13 06:23发布

when a variable is initialize both in local scope as well as global scope how can we use global scope without using this keyword in the same class?

标签: java scope
5条回答
欢心
2楼-- · 2020-02-13 06:45
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 :

查看更多
贪生不怕死
3楼-- · 2020-02-13 06:57
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;
    }
}
查看更多
爷、活的狠高调
4楼-- · 2020-02-13 06:59

If you do not use this it will always be the local variable.

查看更多
地球回转人心会变
5楼-- · 2020-02-13 07:04

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.

查看更多
一纸荒年 Trace。
6楼-- · 2020-02-13 07:12

It is impossible without this. The phenomenon is called variable hiding.

查看更多
登录 后发表回答