Win a copy of Learn Spring Security (video course) this week in the Spring forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Why do I rcv a ClassCastException?

 
Higgledy Smith
Ranch Hand
Posts: 192
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 2409
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I assume that Dog extends Animal. A Dog is an Animal, but an Animal is not necessarily a Dog.
 
Higgledy Smith
Ranch Hand
Posts: 192
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 2409
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 ]
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic