Question about Java polymorphism and casting

后端 未结 9 2312
谎友^
谎友^ 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条回答
  •  旧时难觅i
    2020-12-29 12:32

    Casting an object does not change the object to the object being cast, but allows another class reference that is related to it by inheritance to refer to the object.

    For example C extends E. And they both have a method myName();. If you say

    E e = new C();
    e.myName();
    

    you are calling C myName() method and if you also say

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

    you just told the compiler that it should allow you refer to E with C reference type.

提交回复
热议问题