Java variable scope

落花浮王杯 提交于 2019-12-29 08:23:35

问题


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?


回答1:


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 :

  • Shadowing Declarations
  • what-is-variable-shadowing-used-for-in-a-java-class



回答2:


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




回答3:


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




回答4:


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.




回答5:


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;
    }
}


来源:https://stackoverflow.com/questions/4560850/java-variable-scope

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!