Question about Java polymorphism and casting

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

    the int/double is unrelated; that is a conversion, not a cast - there is no relationship between int and double.

    Re the question; a type's object is fixed at creation. An object that is a C is not (and can never be) an E. However, you can treat an E as a C, since inheritance represents "is a". For example:

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

    Here we still only have one object - simply that the c variable thinks of it as a C, so won't expose methods specific to E (even though the object is an E).

    If we then add:

    E secondE = (E) c;
    

    This is a type check; again, we haven't changed the object, but to put c into an E variable requires us to prove to the compiler/runtime that it really is an E. We didn't need this in the first example as it can already prove that any E is also a C.

    Likewise, with the getClass() - all the cast does is change how the compiler thinks of the object; you haven't changes the object itself. It is still a K.

    You need to separate variables from objects. The cast is talking about the variables; they don't change the object.

提交回复
热议问题