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 Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Just want to confirm if upcasting a Sub Class to a Super Class not allowed in Inheritance?

 
Ranch Hand
Posts: 172
Python MySQL Database Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Report post to moderator



When i run the above code AnimalTest.java I get a class cast exception error. I just need to confirm with you kind folks that is/are my following inferences correct ?
Inference 1: In the try block horse subclass reference variable h is trying to up-cast itself to Animal Super Class so that it could print "Generic Animal eating" when invoked with the eat method as h.eat();
Inference 2: Since Java does not support up casting therefore it throws the ClassCastException error.
Inference 3: So all this boils down to Java allows inheritance to sub classes but gets mad if you try to access its "super" powers.

Sincerely awaiting your reply.
 
Bartender
Posts: 6109
6
Android IntelliJ IDE Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Report post to moderator
Closing as duplicate of https://coderanch.com/t/611160/java/java/confirm-upcasting-Class-Super-Class.

Ashish Dutt, plesae post each question only once.
    Bookmark Topic Watch Topic
  • New Topic