2010-01-25 67 views
2

當調用一個特定的方法時,我讀到Wide和Box是首選,爲什麼不是Box和Wide。任何人都可以用一個小例子來解釋我爲什麼。爲什麼編譯器會嘗試Wide和Box爲什麼不是Box和Wide?

+5

沒有任何語境,我們沒有希望回答這個問題。什麼是「寬」和「盒」?如果你能給出一個你認爲它意味着什麼的小例子,那真的會有所幫助。 – 2010-01-25 16:23:46

+0

+1模糊 – willcodejavaforfood 2010-01-25 16:26:00

+3

我非常肯定,當涉及到Java時,加寬和拳擊是衆所周知的術語。詮釋爲長會擴大,詮釋整數將拳擊。我覺得向網站上聲譽最高的人解釋這一點非常荒謬。 – Powerlord 2010-01-25 16:42:37

回答

7

加寬:呼叫具有較窄參數類型的方法。

public class Test { 
    static void doIt(long l) { } 
    public static void main(String[] args) { 
     int i = 1; 
     doIt(i); // OK: int i is widened to long 
    } 
} 

拳擊:調用一個方法,該方法需要帶有基本參數的包裝類型。

public class Test { 
    static void doIt(Integer i) { } 
    public static void main(String[] args) { 
     int i = 1; 
     doIt(i); // OK: int i is boxed to Integer 
    } 
} 

加寬,然後拳擊:不起作用。

public class Test { 
    static void doIt(Long l) { } 
    public static void main(String[] args) { 
     int i = 1; 
     doIt(i); // FAILS. Cannot widen int to long and then box to Long 
    } 
} 

拳擊,然後加寬:只適用於擴大到超類型。

public class Test { 
    static void doIt(Number n) { } 
    static void go(Long l) { } 
    public static void main(String[] args) { 
     int i = 1; 
     doIt(i); // OK. i is boxed to Integer, and Number is a supertype of Integer 
     go(i); // FAILS: Long is not a supertype of Integer 
    } 
} 
+0

我認爲你已經展示的Wide和Box是可行的因爲你可以將int拓展到long。這就是拓寬的重點。一旦你說出它可以並且你再說它不能。 – GuruKulki 2010-01-25 16:55:40

+0

將示例粘貼到IDE中。我評論過的'FAILS'的代碼給編譯器帶來了錯誤。 – Olivier 2010-01-25 17:04:43

2

答案很簡單:您只可以拓寬元。因此,編譯器必須在加載之前加寬。

0

從SCJP學習資料,我可以告訴你:

當一個方法被調用下面將按此順序進行檢查,如果發現匹配適當的方法將被調用:

1) Widening (preferred: 1st option to be chosen) 
2) Boxing 
3) Var args 

這只是它的工作方式!注意訂單!

+0

是的朋友,但我的問題是爲什麼。任何原因 – GuruKulki 2010-01-25 17:24:35

+0

對不起..我忘了「爲什麼」:) – Andreas 2010-01-25 21:31:37