Question about Java polymorphism and casting

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

    ((M) k).getClass() gives K. Why is that? It was casted to the more general M!

    A useful analogy (that I got from Bill Venners' site artima.com) that may help clear the confusion is that the difference between classes and objects is like the difference between an architect's blueprint and the actual house that is built. The blueprint exists on paper and is a concept, while the house exists in real life. You can have more than one house built to the same blueprint.

    How is that relevant to this question? Let's say there's a McMansion blueprint and a McMansionWithHeatedPool blueprint. A McMansionWithHeatedPool is an extension of a McMansion with a heated pool.

    Now, if you see a real McMansionWithHeatedPool, for that object:

    1. Conceptually (i.e., if you look at the architect's blueprints), you would see that a McMansionWithHeatedPool is clearly also a McMansion. Hence the upcast is allowed. (For the same reason, a McMansion object cannot be type cast into a McMansionWithHeatedPool : no heated pool!)

    2. ((McMansion) k).getClass() gives McMansionWithHeatedPool because k is still a McMansionWithHeatedPool. The type cast is on the expression, not on the object.

提交回复
热议问题