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

Tom :

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!

Eran :

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;
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=74517&siteId=1