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!
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With