0

I have a field and a local variable with same name. How to access the field?

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?

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
Samiey Mehdi
  • 9,184
  • 18
  • 49
  • 63
  • Possible duplicate of [How can I access enclosing class instance variables from inside the anonymous class?](http://stackoverflow.com/questions/15824577/how-can-i-access-enclosing-class-instance-variables-from-inside-the-anonymous-cl) – Bleh Feb 02 '17 at 00:00

4 Answers4

8

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;
    }
}
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
0

You can use "this" keyword to do this.

Example:

public class Test {
private String s = "GLOBAL";

public Test() {
    String s = "LOCAL";
    //System.out.println(this.s);
    //=> OR:
    System.out.println(s);
}


public static void main(String[] args) throws IOException {
    new Test();
}

}

Code4LifeVN
  • 11
  • 2
  • 4
0

Using this keyword you can use the global one but inside the same class. Or simply you can declare global variable static and access the same using classname.variable name.

abcd
  • 3,164
  • 2
  • 18
  • 13
0

Yes you can also use class _ name.Globalvariable_name

Class simple 
{

 static int i;
 public static void main(string args[]) 
  {
      int i=10;
       System.out.println("Local Variable I =" +i) ;
     system.out.println("Global variable I =" +Simple.i) 
   } 

}

Phani
  • 5,319
  • 6
  • 35
  • 43