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?
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
:
Source of the Note and the Rest