• 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 Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Tim Cooke
  • Campbell Ritchie
  • paul wheaton
  • Ron McLeod
  • Devaka Cooray
Sheriffs:
  • Jeanne Boyarsky
  • Liutauras Vilda
  • Paul Clapham
Saloon Keepers:
  • Tim Holloway
  • Carey Brown
  • Piet Souris
Bartenders:

Inheritance and Casting

 
Ranch Hand
Posts: 106
  • 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: 11606
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!
 
reply
    Bookmark Topic Watch Topic
  • New Topic