java - 为什么在类级别不允许泛型中的 super 关键字

标签 java generics inheritance polymorphism

在泛型中

class A<T extends Number>允许

但是

class A<T super Integer>不允许

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

最佳答案

引用 Java Generics: extends, super and wildcards explained :

The super bound is not allowed in class definition.

//this code does not compile !
class Forbidden<X super 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.

关于java - 为什么在类级别不允许泛型中的 super 关键字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37411256/

相关文章:

java - Spring JDBCTemplate - 并发调用

java - System.getProperty ("path.separator")未按预期工作

java方法返回类型

java - 需要了解 "Changes in abstract class will not break code for all inheriting classes"

C++ 方法重载 : base and derived parameters

php - 在 PHP 中获取扩展类的当前工作目录

java - 如何设置一个 View ,当用户单击手机的后退按钮时,它返回到同一个java类中的 View

java - 如何让我的搜索栏覆盖工具栏中的标题?

generics - 为什么泛型的推断不是 "transitive"?

Java 泛型 - 方法覆盖