0

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?

Arun P Johny
  • 376,738
  • 64
  • 519
  • 520

5 Answers5

7
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 :

Community
  • 1
  • 1
jmj
  • 232,312
  • 42
  • 391
  • 431
2

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

fastcodejava
  • 37,849
  • 27
  • 129
  • 182
  • 1
    If there is no variable in local scope with the same name as a instance variable then you can use the instance variable with out the `this` prefix – Arun P Johny Dec 30 '10 at 09:10
2

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

Vladimir Ivanov
  • 42,109
  • 17
  • 76
  • 102
2

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.

Arun P Johny
  • 376,738
  • 64
  • 519
  • 520
2
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;
    }
}
dacwe
  • 42,413
  • 12
  • 112
  • 138
Gopal
  • 625
  • 3
  • 8
  • 18