In the following code, I don't understand why when a1.k()
is called, this.x
in class C
returns 100 instead of 1. My understanding is that this
refers to the current object, but the static type of the current variable a1
is A
. So shouldn't this.x
returns 1, which is the variable for A type?
I mean a1.x
should return 1
, right? Many thanks!
class A {
public int x = 1;
public String k() { return "A" + this.x; }
}
class B extends A {
public int x = 10;
...
}
class C extends B {
public int x = 100;
public String k() { return "C" + this.x; }
}
class TestABC {
public static void main(String[] args) {
A a1 = new C();
C c1 = new C();
System.out.println(a1.k());
}
}