How to access the global variable whenever its name is identical with the local variable?

advertisements

I have a global variable and a local variable with same name. how to access global variable.

Code:

String  s = "Global";
private void mx()
{
   String  s = "Local";
   lblB.setText(s); // i want global
}

In c++ use :: operator like following:

::s

Is were :: operator in Java?


That's not a global variable - it's an instance variable. Just use this:

String  s = "Local";
lblB.setText(this.s);

(See JLS section 15.8.3 for the meaning of this.)

For static variables (which are what people normally mean when they talk about global variables), you'd use the class name to qualify the variable name:

String  s = "Local";
lblB.setText(ClassDeclaringTheVariable.s);

In most cases I prefer not to have a local variable with the same name as an instance or static variable, but the notable exception to this is with constructors and setters, both of which often make sense to have parameters with the same name as instance variables:

public class Person {
    private String name;

    public Person(String name) {
        this.name = name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }
}