Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using a non static variable on a static method through an object? Java

Since we can't use this inside a static method, and we also cannot use non-static variables, why is it that we can use objects, which use nonstatic variables inside static methods?

Here is what I mean:

public int x;
public int y;

public Account(int a, int b) {
    this.x = a;
    this.y = b;
}

public static void Swap(Account acc) {
    int holder;
    holder = acc.x;
    acc.x = acc.y;
    acc.y = holder;
}

So Swap() will work, even though the variables inside of the object are not static. I don't understand this part. Would appreciate some help. TIA!

like image 246
Tom Avatar asked Jan 26 '23 14:01

Tom


1 Answers

static methods cannot access instance variable of the current (this) instance, since no such instance exists in their context.

However, if you pass to them a reference to an instance, they can access any instance variables and methods visible to them.

In case of your swap example, if that method wasn't static, you could have removed the acc argument and operate on the instance variables of this:

public void swap() {
    int holder;
    holder = this.x;
    this.x = this.y;
    this.y = holder;
}
like image 99
Eran Avatar answered Feb 02 '23 11:02

Eran