Question about Java polymorphism and casting

后端 未结 9 2344
谎友^
谎友^ 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:25

    To add to Frederik's answer, casting an object to something doesn't change it's type. Also, object's can only be cast to a type it already is (the compiler just doesn't know at that point) That's why impossible casts will never be accepted:

    Integer i = (Integer) new String();
    

    will not compile, because the compiler knows it can't be possible.

提交回复
热议问题