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?

3
  • 6
    I'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. Commented Dec 30, 2010 at 7:34
  • 2
    Why would you try to avoid using 'this'? That is the way to do it. Commented Dec 30, 2010 at 8:49
  • Given that Java doesn't have global scope, I don't understand the question. Can you please clarify? Commented Dec 30, 2010 at 12:14

5 Answers 5

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 :

Sign up to request clarification or add additional context in comments.

Comments

2

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

1 Comment

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
2

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

Comments

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.

2 Comments

If you are scoping the variable reference with this it will always point to the FIELD variable.
@Vladimir You are right. I've corrected that. It was a mistake.
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;
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.