Explanation of “ClassCastException” in Java

前端 未结 12 1679
小蘑菇
小蘑菇 2020-11-21 11:12

I read some articles written on \"ClassCastException\", but I couldn\'t get a good idea on that. Is there a good article or what would be a brief explanation?

12条回答
  •  北荒
    北荒 (楼主)
    2020-11-21 11:46

    You can better understand ClassCastException and casting once you realize that the JVM cannot guess the unknown. If B is an instance of A it has more class members and methods on the heap than A. The JVM cannot guess how to cast A to B since the mapping target is larger, and the JVM will not know how to fill the additional members.

    But if A was an instance of B, it would be possible, because A is a reference to a complete instance of B, so the mapping will be one-to-one.

提交回复
热议问题