Topic: 一道迷惑的cast题

  Print this page

1.一道迷惑的cast题 Copy to clipboard
Posted by: zming
Posted on: 2004-04-14 12:06

Consider the class hierarchy shown below:
    
  Animal
|
Mammal
/ / \ \
/ / \ \
/ / \ \
/ / \ \
/ / \ \
/ / \ \
/ / \ \
/ / \ \
Dog Cat Raccoon SwampThing
(implements) (implements)
( Washer ) ( Washer )

Consider the following code:
1.  Cat sunflower;
2.  Washer wawa;
3.  SwampThing pogo;
4.  
5.  sunflower = new Cat();
6.  wawa = sunflower;
7.  pogo = (SwampThing)wawa;

Which of the statements below is true?

第7行为什么是运行时错误,而不是编译错误。
pogo = (SwampThing)wawa;
其中wawa是Washer类型和Animal~ SwampThing的层次一点关系也没有,居然不是编译错误。

2.Re:一道迷惑的cast题 [Re: zming] Copy to clipboard
Posted by: zming
Posted on: 2004-04-14 12:12

Consider the class hierarchy shown below:
  
  Animal
   |
  Mammal
  / / \ \
/ / \ \
/ / \ \
/ / \ \
/ / \ \
/ / \ \
/ / \ \
/ / \ \
Dog Cat Raccoon SwampThing
(implements) (implements)
( Washer ) ( Washer )

Consider the following code:
1.  Cat sunflower;
2.  Washer wawa;
3.  SwampThing pogo;
4.  
5.  sunflower = new Cat();
6.  wawa = sunflower;
7.  pogo = (SwampThing)wawa;

Which of the statements below is true?

第7行为什么是运行时错误,而不是编译错误。
pogo = (SwampThing)wawa;
其中wawa是Washer类型和Animal~ SwampThing的层次一点关系也没有,居然不是编译错误。

3.Re:一道迷惑的cast题 [Re: zming] Copy to clipboard
Posted by: zming
Posted on: 2004-04-15 12:28

图示好像不是很清楚,再贴一次。
Consider the class hierarchy shown below:
    
    Animal
     |
    Mammal
    / / \ \
   / / \ \
   / / \ \
   / / \ \
  / / \ \
/ / \ \
/ / \ \
/ / \ \
Dog Cat   Raccoon Swamp
(implements) (implements) Thing
( Washer ) ( Washer )

Consider the following code:

1.  Cat sunflower;
2.  Washer wawa;
3.  SwampThing pogo;
4.  
5.  sunflower = new Cat();
6.  wawa = sunflower;
7.  pogo = (SwampThing)wawa;

Which of the statements below is true?


有谁知道啊?

4.Re:一道迷惑的cast题 [Re: zming] Copy to clipboard
Posted by: zyin006
Posted on: 2004-04-15 19:07

cus wawa's type is interface,pogo's type is class,so no compile error.
but wawa point to Cat object,pogo point to SwampThing object.
so runtime error

5.Re:一道迷惑的cast题 [Re: zming] Copy to clipboard
Posted by: zming
Posted on: 2004-04-19 12:50

i get the total specification in JLS.

JLS Quote:
"If S is a class type: ... If T is an interface type: ... If S is not a final class (§8.1.1), then the cast is always correct at compile time (because even if S does not implement T, a subclass of S might).

If Swampthing were to be a final class it would resu,t in a compile time error.

thanks,zyin006


   Powered by Jute Powerful Forum® Version Jute 1.5.6 Ent
Copyright © 2002-2021 Cjsdn Team. All Righits Reserved. 闽ICP备05005120号-1
客服电话 18559299278    客服信箱 714923@qq.com    客服QQ 714923