• Post Reply Bookmark Topic Watch Topic
  • New Topic

Doubt regarding downcasting and upcasting  RSS feed

 
archu sweet
Ranch Hand
Posts: 66
Android Chrome Eclipse IDE
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


I jus wanted to know what is wrong here which causes the compiler to throw Exception in thread "main" java.lang.ClassCastException: Hi.Dog1 cannot be cast to Hi.Cat5
at Hi.Cat5.main(Cat5.java:8)...error....Please help me out !!
 
Campbell Ritchie
Marshal
Posts: 56525
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
By casting, you are telling the compiler that your Dog is a Cat. The compiler is really naïve and will believe you. Then the JVM finds you are trying to turn a Dog into a cat behind its back and will have nothing of it . . .
 
marc weber
Sheriff
Posts: 11343
Java Mac Safari
  • Likes 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
When you say "new," you are creating a new object. When you say new Dog1(), the type of object you are creating is a Dog1. That is your object, and it will not change.

A reference to that object also has a type. When you say...

Animal animal = new Dog1();

...you are still creating a Dog1 object. But a reference to that Dog1 object is being upcast to type Animal and assigned to the variable, "animal." That's fine, and no explicit cast is needed because it's always true that a Dog1 object IS-AN Animal. Now the variable "animal" can be treated as an Animal, and everything should work fine.

At this point, you could also downcast that reference...

Dog1 myDog = (Dog1)animal;

This is also fine, because the actual object referenced by "animal" is, in fact, a Dog1. But all the compiler knows is that "animal" is some sort of Animal, which might be a Dog1. When you provide the explicit cast, you are telling the compiler, "I'm a programmer, so I know what I'm doing. Trust me, the object referenced here is actually a Dog1." Now the variable "myDog" can be treated as a Dog1, and everything should work fine.

However, when you try this...

Cat5 cat = (Cat5)animal;

...the actual object referenced by "animal" is still a Dog1. Again, all the compiler knows is that "animal" is some sort of Animal, which might be a Cat5. And when you provide the explicit cast, you are telling the compiler, "I'm a programmer, so I know what I'm doing. Trust me, the object referenced here is actually a Cat5." But in this case, what you are telling the compiler is wrong. So at runtime, when it turns out that the object is not really a Cat5, there will be an exception.
 
archu sweet
Ranch Hand
Posts: 66
Android Chrome Eclipse IDE
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
marc weber : Thanks a ton!!....I have understood...Your explanation is too good!!
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!