Question about Java polymorphism and casting

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

    You can't cast objects in Java.

    You can cast references in Java.

    Casting a reference doesn't change anything about the object it refers to. It only produces a reference of a different type pointing to the same object as the initial reference.

    Casting primitive values is different from casting references. In this case the values do change.

提交回复
热议问题