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. mysql - AttributeError: ’module’ object has no attribute ’MatchType’2. php自學從哪里開始?3. javascript - 百度echarts series數據更新問題4. MySQL客戶端吃掉了SQL注解?5. 求大神幫我看看是哪里寫錯了 感謝細心解答6. javascript - JS設置Video視頻對象的currentTime時出現了問題,IE,Edge,火狐,都可以設置,反而chrom卻...7. javascript - 圖片能在網站顯示,但控制臺仍舊報錯403 (Forbidden)8. python小白的基礎問題 關于while循環的嵌套9. phpstady在win10上運行10. python - Django分頁和查詢參數的問題
