Explanation of “ClassCastException” in Java

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

    Do you understand the concept of casting? Casting is the process of type conversion, which is in Java very common because its a statically typed language. Some examples:

    Cast the String "1" to an int -> no problem

    Cast the String "abc" to an int -> raises a ClassCastException

    Or think of a class diagram with Animal.class, Dog.class and Cat.class

    Animal a = new Dog();
    Dog d = (Dog) a; // No problem, the type animal can be casted to a dog, because its a dog.
    Cat c = (Dog) a; // Raises class cast exception; you can't cast a dog to a cat.
    

提交回复
热议问题