Page 1 of 1

Why this exception occurs here

Posted: Wed Jul 26, 2017 10:40 am
by RRRRRR
Please tell me why ClassCastException Occurs here->


class Animal
{}

class Dog extends Animal
{}

class main
{
public static void main(String[] args)

{

Animal animal =new Animal();

Dog d=(Dog) animal; //Complies but gives Runtime Exception(Suppose at line 30).



}

}


According to Sierra Bates->
All the compiler can do is verify that the two types are in same inheritance tree , so that depending on whatever code might have come before the downcast , it's possible that animal is of type Dog.


WHAT DOES THE ABOVE LINES MEANS?? WHY ClassCastException OCCURS AT LINE 30

Re: Why this exception occurs here

Posted: Wed Jul 26, 2017 12:00 pm
by admin
You might want to ask the authors of that book for clarification.
Meanwhile, this discussion should be helpful :
https://stackoverflow.com/questions/907 ... on-in-java