Re: [問題] 泛型的問題
※ 引述《newjoy (職業格鬥家)》之銘言:
: // @ jdk 1.6
: public class GenericTest implements Comparable<String>{
: public int compareTo(Object o)
: {
: return 0;
: }
: public int compareTo(String s)
: {
: return 0;
: }
: public static void main(String[] args) {
: new GenericTest();
: }
: }
: //----
: Comparable的 source code的宣告是 Comparable<T t>
: 請問為什麼上面的public int compareTo(Object o)會發生
: GenericTest.java:1: name clash: compareTo(java.lang.Object) in GenericTest
: and compareTo(T) in java.lang.Comparable<java.lang.String> have the same
: erasure, yet neither overrides the other
: public class GenericTest implements Comparable<String>{
: 明明我有實作了compareTo(String s),
: 那在沒加@Override的情況下compareTo(Object o)也只不過是一個無關的function而已吧?
Comparable<T> interface 實際上是定義了一個 abstract method(經過 erasure):
public abstract int compareTo(Object);
當你定義一個 concrete class(比如你的 GenericTest) implements
Comparable<String>,那麼你需要在 source code 裡明確定義
public int compareTo(String s) {...}
編譯器會將他視為 override Comparable<T>::compareTo(T) method。
細節上來說,編譯器會為上述的 compareTo method 定義產生兩個 method:
public int compareTo(String s) {...}
以及一個 synthetic bridge method:
public int compareTo(Object obj) {
return compareTo((String) obj);
}
(以 JVM spec. 層面來說,後者才是真正 override Comparable<T>::compareTo
method 的 method)
但是在 Java Programming Language level 來說,你不能自己明白定義
compareTo(Object) method。
Generics 引進 Java PL 之後,overriding 的定義稍微變複雜,細節部份請
參閱 Java Language Specification 3rd edition 的
8.4.2 Method Signature 與 8.4.8 內各節。
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 114.24.82.107
※ 編輯: sbrhsieh 來自: 114.24.82.107 (10/30 20:41)
→
10/30 21:26, , 1F
10/30 21:26, 1F
→
10/30 21:27, , 2F
10/30 21:27, 2F
→
10/30 21:34, , 3F
10/30 21:34, 3F
討論串 (同標題文章)