4

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!

Tom
  • 279
  • 1
  • 11
  • a potential reason I could think of is, only the initial input is important, so if the parameter is an object, and it essentially "passes" through the first check (static/non static), the rest is unimportant. Again, not sure so that's the reason I'm asking. – Tom Mar 18 '19 at 06:32
  • 4
    Think about it: what's the difference between accessing `x` and accessing `acc.x`? What is the variable that Java would prevent you from referencing if it were not static? Is `acc` static? – ernest_k Mar 18 '19 at 06:33

2 Answers2

7

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;
}
Eran
  • 387,369
  • 54
  • 702
  • 768
  • Thanks Eran, so my assumption was correct? It essentially "checks" if that input is a static/non static primitive type, and if it isn't, it runs as long as its a reference type. Which then references to non static attributes. The lecturer explained that its a convention to implement swap as static because it doesn't really store anything inside the object.. – Tom Mar 18 '19 at 06:41
  • @user472288 If by "input" you mean the argument to your swap method, that argument cannot be static (it's always a local variable by definition) so there's nothing to check. As long as it's a reference type (i.e. not a primitive type), you have access to all of its visible instance variables and methods. – Eran Mar 18 '19 at 06:52
  • Got it. Thanks dude! – Tom Mar 18 '19 at 06:53
1

You cannot use this in a static method because Java does not know which instance (which this) you refer to.

You can pass a reference to an object as a parameter acc to a static method because the caller specifies which instance to pass.

Java knows which instance you mean when your static method refers to acc. So you can use any accessible fields or methods of acc.

joshp
  • 1,886
  • 2
  • 20
  • 28