SCJP題庫第199題
Given:
10. interface A{void x();}
11. class B implements A{public void x(){} public void y(){}}
12. class C extends B{public void x(){}}
And:
20. java.util.List<A> list = new java.util.ArrayList<A>();
21. list.add(new B());
22. list.add(new C());
23. for(A a : list){
24. a.x();
25. a.y();
26. }
What is the result?
A. The code runs with no output.
B. An exception is thrown at runtime.
C. Compilation fails because of an error in line 20.
D. Compilation fails because of an error in line 21.
E. Compilation fails because of an error in line 23.
F. Compilation fails because of an error in line 25.
Ans: F
解說:
25行出錯是因為取出來的a是A型態,A型態沒有y方法,無法通過編譯器檢查,改法如下:
interface A{void x(); void y(); }
class B implements A{public void x(){} public void y(){}}
class C extends B{public void x(){}}
class test {
public static void main(String[] args){
java.util.List<A> list = new java.util.ArrayList<A>();
list.add(new B());
list.add(new C());
for(A a : list){
a.x();
a.y();
}
}
}
Comments