2009年2月11日 星期三

第80題

Given:
3. interface Fish{}
4. class Perch implements Fish{}
5. class Walleye extends Perch{}
6. class Bluegill{}
7. public class Fisherman {
8. public static void main(String[] args) {
9. Fish f = new Walleye();
10. Walleye w = new Walleye()
11. Bluegill b = new Bluegill();
12. if(f instanceof Perch) System.out.print("f-p ");
13. if(w instanceof Fish) System.out.print("w-f ");
14. if(b instanceof Fish) System.out.print("b-f ");
15. }
16. }
What is the result?
A. w-f
B. f-p w-f
C. w-f b-f
D. f-p w-f b-f
E. Compilation fails.
F. An exception is thrown at runtime.
答案:B
參考:7-8 物件的轉型解析
---------------------------------------------------------
考instanceof 的運算符號
12. if(f instanceof Perch) System.out.print("f-p ");
>>9. Fish f = new Walleye();
>>5. class Walleye extends Perch{} //Walleye 和Perch是父子關係故(f instanceof Perch)=true
13. if(w instanceof Fish) System.out.print("w-f ");
>>10. Walleye w = new Walleye()
>>5. class Walleye extends Perch{} //Walleye 和Fish是父子關係
>>4. class Perch implements Fish{} //Walleye 和Fish是父子關係故(w instanceof Fish)=true
14. if(b instanceof Fish) System.out.print("b-f "); //b 和Fish沒任何關係

沒有留言:

張貼留言