class A {int x = 5;}
class B extends A {int x = 10;}
class D {
public static void main(String[] args){
A b0 = new B();
System.out.print(b0.x);
}
}
I am wondering why this code prints 5 instead of 10.
If I instead write the following, converting the variables x to methods, it works more as I'd expect, and prints out 10, since at compile time it merely checked if b0's static type, A, has a method x, and then at runtime, uses b0's dynamic type, B, to run x.
class A {int x() {return 5;}}
class B extends A {int x() {return 10;}}
class D {
public static void main(String[] args){
A b0 = new B();
System.out.print(b0.x());
}
}
My theory is that instance variables are looked up statically unlike methods, but I am not sure about why that would be.
Thanks!