Explanation of “ClassCastException” in Java

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

    Consider an example,

    class Animal {
        public void eat(String str) {
            System.out.println("Eating for grass");
        }
    }
    
    class Goat extends Animal {
        public void eat(String str) {
            System.out.println("blank");
        }
    }
    
    class Another extends Goat{
      public void eat(String str) {
            System.out.println("another");
      }
    }
    
    public class InheritanceSample {
        public static void main(String[] args) {
            Animal a = new Animal();
            Another t5 = (Another) new Goat();
        }
    }
    

    At Another t5 = (Another) new Goat(): you will get a ClassCastException because you cannot create an instance of the Another class using Goat.

    Note: The conversion is valid only in cases where a class extends a parent class and the child class is casted to its parent class.

    How to deal with the ClassCastException:

    1. Be careful when trying to cast an object of a class into another class. Ensure that the new type belongs to one of its parent classes.
    2. You can prevent the ClassCastException by using Generics, because Generics provide compile time checks and can be used to develop type-safe applications.

    Source of the Note and the Rest

提交回复
热议问题