SCJP 1.6版考題 173

出自 陳富國維基館
前往: 導覽搜尋
Given:
11. public class Yikes{
12.
13.   public static void go(Long n){System.out.print("Long ");}
14.   public static void go(Short n){System. outprint("Short ");}
15.   public static void go(int n){System.out.print("int ");}
16.   public static void main(String[] args){
17.     short y = 6;
18.     long z = 7;
19.     go(y);
20.     go(z);
21.   }
22. }

What is the result?
 A. int Long
 B. Short Long
 C. Compilation fails.
 D. An exception is thrown at runtime.

解答


Ans: A

解說:

go(y)會代15行的go方法,short可以自動提升至int 
 (那為什麼不採取Short的第14行go?變成Short物件會比單純16位元轉成32位元要複雜)
go(z)z是long,不可能代入15行的go,所以就用13行的go,z會auto-boxing成Long物件