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?
Asked
Active
Viewed 2,223 times
0

Arun P Johny
- 384,651
- 66
- 527
- 531

neha kapor
- 9
- 2
-
6I'm not sure what you mean by "global scope" in the context of Java. A code sample would go a long way for this question. – Tyler Dec 30 '10 at 07:34
-
2Why would you try to avoid using 'this'? That is the way to do it. – StaxMan Dec 30 '10 at 08:49
-
Given that Java doesn't *have* global scope, I don't understand the question. Can you please clarify? – Jörg W Mittag Dec 30 '10 at 12:14
5 Answers
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 :
2
If you do not use this
it will always be the local variable.

fastcodejava
- 39,895
- 28
- 133
- 186
-
1If 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,730
- 18
- 77
- 103
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
- 384,651
- 66
- 527
- 531
-
1If you are scoping the variable reference with this it will always point to the FIELD variable. – Vladimir Ivanov Dec 30 '10 at 08:03
-