Why this exception occurs here

Help and support on OCA OCP Java Programmer Certification Questions
1Z0-808, 1Z0-809, 1Z0-815, 1Z0-816, 1Z0-817

Moderator: admin

Post Reply
RRRRRR
Posts: 26
Joined: Sun Jul 23, 2017 2:13 am
Contact:

Why this exception occurs here

Post 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

admin
Site Admin
Posts: 10388
Joined: Fri Sep 10, 2010 9:26 pm
Contact:

Re: Why this exception occurs here

Post 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

Post Reply

Who is online

Users browsing this forum: Google [Bot] and 43 guests