Java泛型的編譯問題
問題描述
源代碼如下跳至下面提示符,這段代碼顯然是無法編譯的
我認(rèn)為一個原因是
BoundedEcho<String> stringEcho = new BoundedEcho<String>();
這里的String無法繼承Number,他不是String的子類?這樣理解對么?
然后另一個問題是,最后那段我傳入了一個new BoundedEcho<Integer> object, 而且他是BoundedEcho<T>的, 為什么這里會報錯呢?
是否將BoundedEcho改為public class BoundedEcho<? extends Number> {...}就對了?
源代碼在這里
public class BoundedEcho<T extends Number> { public T echo(T value) {return value; } public BoundedEcho<T> echo(BoundedEcho<T> value) {return value; }}
public class BoundedEchoChamber{ public static void main(String[] args) {BoundedEcho<Number> numberEcho = new BoundedEcho<Number>();numberEcho.echo(10);numberEcho.echo(10d);numberEcho.echo(10f);numberEcho.echo(10L); BoundedEcho<String> stringEcho = new BoundedEcho<String>();numberEcho.echo(new BoundedEcho<Integer>());numberEcho.echo(new BoundedEcho<Double>());numberEcho.echo(new BoundedEcho<Float>());numberEcho.echo(new BoundedEcho<Long>()); }}
問題解答
回答1:問題出在這兩句
public BoundedEcho<T> echo(BoundedEcho<T> value) {return value; } BoundedEcho<Number> numberEcho = new BoundedEcho<Number>();
實例化的時候你把T聲明成了Number,之后調(diào)用就必須是BoundedEcho<Number>。原因是BoundedEcho<Integer>等類型和BoundedEcho<Number>是不同的類,并不存在繼承關(guān)系。
相關(guān)文章:
1. Span標(biāo)簽2. css - 求推薦適用于vue2的框架 像bootstrap這種類型的3. docker-machine添加一個已有的docker主機問題4. css - 關(guān)于div自適應(yīng)問題,大家看圖吧,說不清5. 關(guān)docker hub上有些鏡像的tag被標(biāo)記““This image has vulnerabilities””6. SessionNotFoundException:會話ID為null。調(diào)用quit()后使用WebDriver嗎?(硒)7. android新手一枚,android使用httclient獲取服務(wù)器端數(shù)據(jù)失敗,但是用java工程運行就可以成功獲取。8. angular.js使用$resource服務(wù)把數(shù)據(jù)存入mongodb的問題。9. java - Collections類里的swap函數(shù),源碼為什么要新定義一個final的List型變量l指向傳入的list?10. python - django如何每次調(diào)用標(biāo)簽的時候都取隨機數(shù)據(jù)
