0

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:

  1. Why is C.x() called instead of B.x()? Why does Java remember a variable's original type after it's been cast to a new type?
  2. 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();
    }
}
Itschotsch
  • 40
  • 1
  • 6
  • 1
    Because casting does not change any type. It really is not up to you to decide to call `B.x()`. – luk2302 Jan 10 '22 at 20:54
  • 1
    (1) Polymorphic methods (those which are not final, or private or static) don't care about type of *variable* but only care about type of *object* on which method is executed. That is what polymorphism is all about. – Pshemo Jan 10 '22 at 20:55
  • Thanks. This is interesting because I tried out the same thing in C++ and the output was B. In C#, though, the output was C as well. Slightly confusing. – Itschotsch Jan 10 '22 at 21:26

0 Answers0