• Post Reply Bookmark Topic Watch Topic
  • New Topic

Casting and Interfaces  RSS feed

 
John Mulholland
Ranch Hand
Posts: 40
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Guys could anyone help me understand what is going on here ?


I generally understand the how casting works, and how ClassCastExceptions are thrown - but I don't understand why pear=(Pear)orange would compile ? Pear and Orange are not in an inheritance relationship so surely the compiler knows that orange could NEVER be of type Pear.

Also (and confusingly) if I declare Pear to be a class (not an interface) the result is different - that I REALLY don't get !

Any help would be very much appreciated - as always.
 
Stephan van Hulst
Saloon Keeper
Posts: 7973
143
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
John Mulholland wrote:surely the compiler knows that orange could NEVER be of type Pear.


This is not true:



You can not do this if Pear is a class, because then the compiler CAN actually determine that an Orange can never be a Pear, because of Single Inheritance.
 
John Mulholland
Ranch Hand
Posts: 40
  • Likes 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Stephan. I see now that even though Orange (class) and Pear (interface) are not related :

- a ref variable of type Orange COULD refer to an object of a subclass which implements Pear
- that subclass object would have an IS-A relationship with Pear (and therefore the could be upcast to a Pear)

Because that COULD happen (determined at runtime when the object is created and assigned to Orange ref variable), the code will compile
and IF the object created turns out not to implement Pear then a ClassCastException will be thrown.

Thanks for your help - I get it now



 
Stephan van Hulst
Saloon Keeper
Posts: 7973
143
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Great job, happy it helped
 
Don't get me started about those stupid light bulbs.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!