Win a copy of Mastering Corda: Blockchain for Java Developers this week in the Cloud/Virtualization forum!
  • 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
  • Paul Clapham
  • Ron McLeod
  • Bear Bibeault
  • Liutauras Vilda
Sheriffs:
  • Jeanne Boyarsky
  • Tim Cooke
  • Junilu Lacar
Saloon Keepers:
  • Tim Moores
  • Tim Holloway
  • Stephan van Hulst
  • Jj Roberts
  • Carey Brown
Bartenders:
  • salvin francis
  • Frits Walraven
  • Piet Souris

Inheritance and Casting

 
Ranch Hand
Posts: 104
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
The following diagram is given below along with the corresponding assignments:



In the above example
1) line 1 is given
2) line 2 represents Upcasting (You are assigning a subclass reference "x" to a parent class reference "a")
3) line 3 causes a ClassCastException because variable "x" is not a Human
4) Line 4 compiles and runs (reference variable x is referred to by an "Animal" reference variable "a")
5) Line 5 compiles and runs
6) line 6 causes a ClassCastException because Mammal is not a Human
7) line 7- Type mismatch: cannot convert from Animal to Mammal



Question: How does the double cast on line 5 work?

Mammal b = (Mammal) (Animal)x; // line 5 - Compiles and Runs

Lines 5 and 7 are almost the same except for line 5 contains (Mammal).
I am interested in knowing what enables line 5 to compile and run.

 
Sheriff
Posts: 11604
178
Hibernate jQuery Eclipse IDE Spring MySQL Database AngularJS Tomcat Server Chrome Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Line 5

can be rewritten to:



Thomas Hauck wrote:I am interested in knowing what enables line 5 to compile and run.


Why do you think it would not compile? x is a Mammal. So first of all you cast it explicitly to an Animal (that's similar to line 2, where the cast happens implicitly). And then you cast the temporary result back to a Mammal (the object to which the temporary result is referring is still a Mammal, so no problem at all).

If in line 7 the type of variable b1 would be changed to Animal (instead of Mammal) that line would compile and run without any problem (and you have exactly the same line as in the rewritten line 5).

Hope it helps!
 
The glass is neither half full or half empty. It is too big. But this tiny ad is just right:
Building a Better World in your Backyard by Paul Wheaton and Shawn Klassen-Koop
https://coderanch.com/wiki/718759/books/Building-World-Backyard-Paul-Wheaton
reply
    Bookmark Topic Watch Topic
  • New Topic