This week's book giveaway is in the Design forum.
We're giving away four copies of Design for the Mind and have Victor S. Yocco on-line!
See this thread for details.
Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Dan's Reference Conversion Doubt

 
Jas Oberai
Ranch Hand
Posts: 231
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Friends,
This question is from Dan's Questionaire,i am not able to understand the
wordings,can you please tell me what the author means to convey here,and
how can the error be removed from this code.Thanks.

[ May 12, 2005: Message edited by: jas oberai ]
 
Rohan Kayan
Ranch Hand
Posts: 123
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

interface I1 {}
interface I2 {}
class Base implements I1 {}
class Sub extends Base implements I2 {}
class Silver
{
public static void main(String []args)
{
Base[] base = {new Base()};
Sub sub[] = new Sub[1]; // 1
Object obj = base; // 2
sub = (Sub[])obj; // 3
I1 []i1 = (I1[])obj; // 4
}
}


Actually at the compile time it will allow , as we are implicit downcasting.
But at the run time it will check for the actual object in this case the actual object refered by obj is of Base type that's why it will give error . To remove the change

Object obj = sub; // 2
 
Timmy Marks
Ranch Hand
Posts: 226
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Simple explaination:

All Women are People, so if you have a Woman you know she is a Person

but

All People are not Women, so if you have a Person you cannot "cast" is as a Woman

now substitute Base for People and Sub for Women and you can see why it is a mistake.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic