• Post Reply Bookmark Topic Watch Topic
  • New Topic

Classcast Exception  RSS feed

 
Vaibhav G Garg
Ranch Hand
Posts: 143
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

I am trying to cast a parent object to a child reference but it is giving me ClassCastException.

Below is the code snippet:



As per my understanding, it should work fine since both the classes are in Inheritance tree and hence, there should not be any issue. But, it is giving exception at run time for class casting. Please explain the reason of this exception.
 
Marc Cracco
Ranch Hand
Posts: 80
1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You're trying to make a Parent object a Child object which you can't.

If you had a class Car and a class Ford that extended Car. A Ford IS a Car but not all Cars are Fords. In your case your trying to force a Car to be a Ford but it could be a Honda so you're getting an Exception.

Checkout the tutorial.
 
Ariel Krakowski
Greenhorn
Posts: 5
Chrome Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You can't cast a Parent instance to a Child instance! Casting Objects is used when the superclass really is an instance of the subclass, but that's not the case in your code.

For example, this code should work, since you know vehicle is really a Truck:

Truck truck1 = new Truck();
Vehicle vehicle = truck;
Truck truck2 = (Truck) vehicle;
 
Aki Mohan
Ranch Hand
Posts: 99
Eclipse IDE Firefox Browser Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Vaibhav

In Java, superclass has no idea about the members and methods inside the derived class, but the derived classes have full knowledge about the superclass. Now, what you're trying to do is make a Superclass object and telling it to behave as the derived class and DANG... That's not polymorphism. It will compile but will throw RuntimeException - ClassCastException. I hope it helps.

Peace
Aakash
 
Consider Paul's rocket mass heater.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!