Question about Java polymorphism and casting

后端 未结 9 2306
谎友^
谎友^ 2020-12-29 12:02

I have a class C. Class E extends it.

E e = new E();
C c = new C();

Why is

e = (E) c;

Upon further review

9条回答
  •  既然无缘
    2020-12-29 12:22

    "If the compiler treats it as an M, it should execute M's methods."
    The compiler treats the reference as M. The instance that the reference points to is of type K, not M. You can't cast the reference and assume that means the instance will suddenly change behavior. What the compiler does is make sure that the method you invoke on the specified reference exists. It does not have anything to do with which implementation is invoked, only that an implementation does exist.

提交回复
热议问题