Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 956
daremkd Avatar asked Jun 03 '26 18:06

daremkd


2 Answers

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);
}
like image 195
Eng.Fouad Avatar answered Jun 06 '26 08:06

Eng.Fouad


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.

like image 35
moonwave99 Avatar answered Jun 06 '26 07:06

moonwave99



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!