日期:2014-05-20  浏览次数:20591 次

麻烦各位帮我看看这道题 谢谢
1. interface Animal {
2. void soundOff();
3. }
4.
5. class Elephant implements Animal {
6. public void soundOff() {
7. System.out.println(“Trumpet”);
8. }
9. }
10.
11. class Lion implements Animal {
12. public void soundOff() {
13. System.out.println(“Roar”);
14. }
15. }
16.
17. class Alpha1 {
18. static Animal get( String choice ) {
19. if ( choice.equalsIgnoreCase( “meat eater” )) {
20. return new Lion();
21. } else {
22. return new Elephant();
23. }
24. }
25. }
Which compiles?
A. new Animal().soundOff();
B. Elephant e = new Alpha1();
C. Lion 1 = Alpha.get(“meat eater”);
D. new Alpha1().get(“veggie”).soundOff();
Answer: D

答案c错在哪?

------解决方案--------------------
Alpha.get(“meat eater”)在运行期才能确定,再说运行期返回的也是Animal对象,这是面对抽象编程的概念
------解决方案--------------------
Alpha.get(“meat eater”); 
这里假设Alpha就是Alpha1 。返回的是Animal。是Lion的父类,在java中,父类转换为子类必须强制转换,当然前提是父类所引用的对象实际上是该子类的对象,否则会出错。