• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Liutauras Vilda
  • Bear Bibeault
  • Paul Clapham
  • Jeanne Boyarsky
Sheriffs:
  • Devaka Cooray
  • Junilu Lacar
  • Tim Cooke
Saloon Keepers:
  • Tim Moores
  • Ron McLeod
  • Tim Holloway
  • Claude Moore
  • Stephan van Hulst
Bartenders:
  • Winston Gutkowski
  • Carey Brown
  • Frits Walraven

how to resolve this classcastexception issue in polymorphism case in java?  RSS feed

 
Greenhorn
Posts: 21
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


My question in the above code why does Car car2 = (Car) new Automobile(); give error ? Even though I did casting from super to subclass, still I couldn't fix up the issue.
error I got:

Driving electric carException in thread "main" Driving car java.lang.ClassCastException: vehicles.Automobile cannot be cast to vehicles.Car at vehicles.ElectricCar.main(ElectricCar.java:16)
 
Marshal
Posts: 63461
207
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You can only cast a reference type towards Object or towards its runtime type; since the runtime type of that object is Automobile, you are casting away from its runtime type.
A Car IS AN Automobile in your program, but there is no guarantee that an Automobile is a Car.
 
Consider Paul's rocket mass heater.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!