Explanation of “ClassCastException” in Java

前端 未结 12 1874
小蘑菇
小蘑菇 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:44

    It's really pretty simple: if you are trying to typecast an object of class A into an object of class B, and they aren't compatible, you get a class cast exception.

    Let's think of a collection of classes.

    class A {...}
    class B extends A {...}
    class C extends A {...}
    
    1. You can cast any of these things to Object, because all Java classes inherit from Object.
    2. You can cast either B or C to A, because they're both "kinds of" A
    3. You can cast a reference to an A object to B only if the real object is a B.
    4. You can't cast a B to a C even though they're both A's.

提交回复
热议问题