Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

casting

 
dolly shah
Ranch Hand
Posts: 383
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


Z & Y are sibling objects here. Line 1 fails at runtime but why it compiles?
 
ahmed yehia
Ranch Hand
Posts: 424
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Z y2 = (Z)y; //line 1

'y' is a variable of type 'X' that refers to an object of type 'Y' and you are casting it to type 'Z' which is a sub class of 'X' so it pass at compile time. Had it been of type 'Y' Not 'X' then it wouldnt compile.
 
dolly shah
Ranch Hand
Posts: 383
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Ahmed I got it. I was little confuse.
 
yogesh sood
Ranch Hand
Posts: 108
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Dolly,

You should have look at this from Corey, to understand how it works for Interfaces.

 
camilo lopes
Ranch Hand
Posts: 202
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You can not convert a car on a bike, only because both are vehicles. See the problem that prevents the compiler?
I hope I have helped!
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic