SCJP 1.6版考題 080

出自 陳富國維基館
於 2013年3月30日 (六) 06:12 由 Ikk (對話 | 貢獻) 所做的修訂 (新頁面: 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) ...)
(差異) ←上個修訂 | 最新修訂 (差異) | 下個修訂→ (差異)
前往: 導覽搜尋
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.


解答


Ans: B

解說:

f instanceof Perch是判斷f所指向的物件型態是否為Perch, 
   f是指向Walleye物件,Walleye繼承Perch,所以12行if為true
w instanceof Fish是true,w是指向Walleye物件,
   Walleye繼承Perch,Perch實作Fish,所以Walleye也是Fish的型態
Bluegill類別與Fish沒有任何繼承關聯,所以b instanceof Fish為false