简体   繁体   English

当其名称与参数变量相同时,调用实例变量

[英]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. 参数final x和实例x具有相同的名称。 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? 如果我想在go()方法中使用它,我将如何引用实例变量x = 12,因为它的名称与参数变量相同?

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 : 或者使用实例方法,并使用关键字this引用实例x

int x = 12;

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

this.x points to the instance variable. this.x指向实例变量。

In order to refer to an instance variable, you have to be in a real instance: your method should not be static then. 为了引用一个实例变量,你必须在一个真实的实例中:你的方法不应该是static

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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