Java: this points to caller for methods, but to current class for variables. Why?

So the following code outputs

In B m  
In A m  
In B m2  
2

Code:

class A {
  int y = 1;

  int m() {
    System.out.println("In A m");
    return this.m2();
  }

  int m2() {
    System.out.println("In A m2");
    return y;
  }
}

class B extends A {
  int y = 2;

  int m() {
    System.out.println("In B m");
    return super.m();
  }

  int m2() {
    System.out.println("In B m2");
    return y;
    }
}

class C extends B {
  int y = 3;

  int m() {
    return super.m();
  }

  public static void main(String args[]) {
    System.out.println(new C().m());
  }
}

This is rather confusing to me.

I understand that B’s m2() is the m2 function that gets called. This makes sense because this.m2() refers to the caller’s m2, and C’s m2 is B’s m2.

However, m2 doesn’t use C’s y variable, it uses B’s y variable.

Shouldn’t this.y point to C’s y ? Why does it use B’s y instead?

Answer

Polymorphism only works for methods.

Thus: methods get overwritten, fields not so. In other words: if you run a method from B, then y is 2. Meaning: there are actually three different values of y, and your example will make use the B version of y.

Try changing y to be protected to change that.

But polymorphism is important here: as the call to m2 in A actually invokes B m2() that finally returns 2.

Leave a Reply

Your email address will not be published. Required fields are marked *