• 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
  • Tim Cooke
  • Junilu Lacar
Sheriffs:
  • Paul Clapham
  • Devaka Cooray
  • Knute Snortum
Saloon Keepers:
  • Ron McLeod
  • Tim Moores
  • Stephan van Hulst
  • Tim Holloway
  • Frits Walraven
Bartenders:
  • Carey Brown
  • salvin francis
  • Claude Moore

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

 
Ranch Hand
Posts: 39
  • 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: 64172
215
  • 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.
 
"I know this defies the law of gravity... but I never studied law." -B. Bunny Defiant tiny ad:
Create Edit Print & Convert PDF Using Free API with Java
https://coderanch.com/wiki/703735/Create-Convert-PDF-Free-Spire
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!