Explanation of “ClassCastException” in Java

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

    It is an Exception which occurs if you attempt to downcast a class, but in fact the class is not of that type.

    Consider this heirarchy:

    Object -> Animal -> Dog

    You might have a method called:

     public void manipulate(Object o) {
         Dog d = (Dog) o;
     }
    

    If called with this code:

     Animal a = new Animal();
     manipulate(a);
    

    It will compile just fine, but at runtime you will get a ClassCastException because o was in fact an Animal, not a Dog.

    In later versions of Java you do get a compiler warning unless you do:

     Dog d;
     if(o instanceof Dog) {
         d = (Dog) o;
     } else {
         //what you need to do if not
     }
    

提交回复
热议问题