class A {
int i = 1;
int f() { return i; }
}
class B extends A {
int i = 2;
int @Override f() { return -i; }
}
public class override_test {
public static void main(String args[]) {
B b = new B();
A a = (A) b; // Cast b to an instance of class A.
System.out.println(a.i); // Now refers to A.i; prints 1;
System.out.println(a.f()); // Still refers to B.f(); prints -2;
}
}
I am wondering why a.f() still refers to B.f() while a.i refers to A.i.
thanks in advance!
Simple rule is when you call a method, it will be on instance type (polymorphism) in this case instance is of type
Beven though reference is of typeA.When you call variable, it will be on Type of the reference.
Read more about Ploymorphism