I encountered a piece of code similar to the one below and was sure that its output would be B
, since the variable y
is cast to class B
before calling x()
, but instead, the program prints C
. So I have two questions:
- Why is
C.x()
called instead ofB.x()
? Why does Java remember a variable's original type after it's been cast to a new type? - How would I call
B.x()
?
class A {
public void x() {
System.out.println("A");
}
}
class B extends A {
@Override
public void x() {
System.out.println("B");
}
}
class C extends B {
@Override
public void x() {
System.out.println("C");
}
}
public class Main {
public static void main(String args[]) {
A y = new C();
((B)y).x();
}
}