为什么在类级别不允许泛型中的超级关键字 [英] Why super keyword in generics is not allowed at class level

查看:78
本文介绍了为什么在类级别不允许泛型中的超级关键字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

泛型

class A<T extends Number>

但是

class A<T super Integer>不允许

我不明白这一点.这听起来像是新手问题,但我陷入其中

I'm not getting this point. This may sound like novice question but I'm stuck in it

推荐答案

引用 Java泛型:扩展,超级和通配符解释:

在类定义中不允许超界.

The super bound is not allowed in class definition.

//this code does not compile !
class Forbidden<X super Vehicle> { }

为什么?因为这样的构造没有意义.例如,您不能使用Vehicle擦除type参数,因为可以使用Object实例化Forbidden类.因此,无论如何,您都必须擦除对象的类型参数.如果考虑禁止类,它可以代替X的任何值,而不仅仅是Vehicle的超类.使用超级绑定是没有意义的,它不会为我们带来任何好处.因此,这是不允许的.

Why? Because such construction doesn't make sense. For example, you can't erase the type parameter with Vehicle because the class Forbidden could be instantiated with Object. So you have to erase type parameters to Object anyway. If think about class Forbidden, it can take any value in place of X, not only superclasses of Vehicle. There's no point in using super bound, it wouldn't get us anything. Thus it is not allowed.

这篇关于为什么在类级别不允许泛型中的超级关键字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆