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. python - TypeError: tryMsgcode() takes exactly 2 arguments (0 given)2. mysql - 数据库JOIN查询3. 微信扫码跳转页面是怎么实现的4. python - scrapy-redis爬虫运行是连接redis数据库连接错误5. mysql group by多个字段6. python - 求一个在def中可以实现调用本def满足特定条件continue效果的方法(标题说不太清楚,请见题内描述)7. python - requests post问题8. service mysql.server start 启动失败9. php - mysql中,作为主键的字段,用int类型,是不是比用char类型的效率更高?10. 关于python的继承的一个疑问

网公网安备