Java Variable Area

when a variable is initialized both in the local scope and in the global scope, how can we use the global scope without using a keyword thisin the same class?

0
source share
5 answers
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    
    }    
}  

See also:

+7
source

If you are not using this, it will always be a local variable.

+2
source

. .

+2

If you are viewing a variable reference with this, it will always point to an instance variable.

If a method declares a local variable with the same name as a class level variable, the first will be the โ€œshadowโ€ of the last. To access a class level variable from inside the method body, use this keyword.

+2
source
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;
    }
}
+2
source

All Articles