Win a copy of The Little Book of Impediments (e-book only) this week in the Agile and Other Processes forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Inheritance and Casting

 
Thomas Hauck
Ranch Hand
Posts: 95
  • Mark post as helpful
  • send pies
  • 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.

 
Roel De Nijs
Sheriff
Posts: 10662
144
AngularJS Chrome Eclipse IDE Hibernate Java jQuery MySQL Database Spring Tomcat Server
  • Mark post as helpful
  • send pies
  • 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!
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic