Ok Matt , here a small program for you.Hope this will help you as to when it gives classcastexception in runtime.
public class Human
{
public static void main(String args[])
{
System.out.println("I am human");
}
}
public class Man extends Human
{
public static void main(String args[])
{
System.out.println("I am a man");
}
}
Look at this class carefully.
1. public class Woman extends Human
2.{
3. public static void main(String args[])
4. {
5. System.out.println(" I am a woman");
6. Human human = new Man();
7. Woman woman = new Woman();
8. //woman = human; (if you uncomment this line compiler complains)
9. woman =(Woman) human; //(Do this ,it compile but throw an exception during runtime)
10. System.out.println("This
test Failed");
}
}
Here I am created a class Woman which extends Human.
Look at line 6 , its perfectly legal as Man in subclass of Human no casting required.
If you uncomment line 8(and comment line 9) compiler complains
as " Explicit cast needed to convert Human to Woman".
So on line 9 we do a explicit casting and it compiled fine.But at runtime the compiler sees that actually human is reference to a Man ,that is, we have tried to equate a man to a woman which upsets compiler and hence a "classcastexception " is thrown at runtime.
Hope this helps........