简体   繁体   中英

Call an instance variable when its name is same with the argument variable

I have this code:

class Foo {
 int x = 12;

public static void go(final int x) {

    System.out.println(x);

}
}

The argument final x and the instance x have the same name. How would I refer to the instance variable x = 12 if I want to use it in the go() method considering its name is the same with the argument variable?

You need to make it static in order to use it within static method:

static int x = 12;

Then you can get a reference to it via the class name:

public static void go(final int x)
{
    System.out.println(Foo.x);
}

Or alternatively, create an instance and use it locally:

int x = 12;

public static void go(final int x)
{
    Foo f = new Foo();
    System.out.println(f.x);
}

Or use instance method, and refer to the instance x with the keyword this :

int x = 12;

public void go(final int x)
{
    System.out.println(this.x);
}

this.x points to the instance variable.

In order to refer to an instance variable, you have to be in a real instance: your method should not be static then.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM