jQuery in Action, 2nd edition*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Why do I rcv a ClassCastException? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Why do I rcv a ClassCastException?" Watch "Why do I rcv a ClassCastException?" New topic
Author

Why do I rcv a ClassCastException?

Higgledy Smith
Ranch Hand

Joined: Mar 07, 2006
Posts: 192
public class DogTest {
public static void main (String[] Args) {
Animal animal = new Animal();
Dog d = (Dog) animal;
}
}

Why at runtime do I get an exception?
Keith Lynn
Ranch Hand

Joined: Feb 07, 2005
Posts: 2367
I assume that Dog extends Animal. A Dog is an Animal, but an Animal is not necessarily a Dog.
Higgledy Smith
Ranch Hand

Joined: Mar 07, 2006
Posts: 192
SO if add this:

if (animal instanceof Dog) {
Dog d = (Dog) animal;
}

The compiler will recognize that animal is a dog? (in this instance) But, if this is true, why am I getting a runtime error?
Keith Lynn
Ranch Hand

Joined: Feb 07, 2005
Posts: 2367
Originally posted by Higgledy Smith:
SO if add this:

if (animal instanceof Dog) {
Dog d = (Dog) animal;
}

The compiler will recognize that animal is a dog? (in this instance) But, if this is true, why am I getting a runtime error?


The problem is that you are creating an Animal object by using its constructor. Even though Dog is a subclass of Animal, because the runtime type of the object is Animal, you cannot cast it to one of its subclasses.

The above code you mention would prevent the line from being executed, but in your original code, animal is an Animal.

Also the compiler is simply checking that the cast is appropriate syntax. It is valid syntactically to cast a superclass type to a subclass type. However, at runtime, the interpreter will know whether the cast is appropriate.
[ March 13, 2006: Message edited by: Keith Lynn ]
 
 
subject: Why do I rcv a ClassCastException?
 
Similar Threads
Reference Variable Casting
Inheritence and Typecasting in java
Problems with Lists
Generics Help please !
Questio about castdown and ClassCastException (Certification)