Java泛型的編譯問題
問題描述
源代碼如下跳至下面提示符,這段代碼顯然是無法編譯的
我認為一個原因是
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,之后調用就必須是BoundedEcho<Number>。原因是BoundedEcho<Integer>等類型和BoundedEcho<Number>是不同的類,并不存在繼承關系。
相關文章:
1. docker-machine添加一個已有的docker主機問題2. javascript - 新建js文件時如何自動地加上"use strict"?3. javascript - 如何獲取未來元素的父元素在頁面中所有相同元素中是第幾個?4. apache - nginx 日志刪除后 重新建一個文件 就打不了日志了5. node.js - node express 中ajax post請求參數接收不到?6. java - 原生CGLib內部方法互相調用時可以代理,但基于CGLib的Spring AOP卻代理失效,為什么?7. java - tomcat服務經常晚上會掛,求解?8. javascript - 用jsonp抓取qq音樂總是說回調函數沒有定義9. windows-7 - Win7中Vmware Workstatoin與Xampp中Apache服務器端口沖突?10. javascript - 新浪微博網頁版的字數限制是怎么做的
