简体   繁体   English

为什么我们不能扩展泛型?

[英]Why can't we extend a generic type?

We have the following code: 我们有以下代码:

class MyClass<T>{
...
}
class MyExtendedClass extends MyClass<T>{//Compile error
...
}

I've tried to create non generic class which is a subtype of the generic class. 我试图创建非通用类,它是通用类的子类型。 Why is it forbidden? 为什么禁止它?

You should either put in a concrete class there: 您应该在那里放置一个具体的类:

class MyExtendedClass extends MyClass<String>

Or add a generic class to your subclass 或将通用类添加到您的子类中

class MyExtendedClass<T> extends MyClass<T>

The way you use it now, what would you expect to be the type of T when you declare an instance of MyExtendedClass as follows: 现在使用它的方式,当声明MyExtendedClass的实例时,您期望的T类型是什么:

MyExtendedClass x = new MyExtendedClass();

There is no way to tell what T should be in that case! 在这种情况下,没有办法说出T应该是多少!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 通用扩展不能添加相同的类型 - Generic extend can't add the same type 为什么不能扩展接口“泛型方法”并将其类型缩小到继承的接口“类通用”? - Why can't I extend an interface “generic method” and narrow its type to my inherited interface “class generic”? 为什么不能扩展通用类型 - Why Can't Collection Generic Type be Extended 如果我们可以使用原始类型,为什么在 Java 中使用 generics 时需要扩展? - Why do we need to extend when using generics in Java if we can just use the original type? 为什么不能将包含通用类型的通用类型分配给通配符类型的通用类型的类 - Why can't a Generic type containing a Generic type be assigned to a Generic typed class of wildcard type 为什么我们可以创建通用模板的新实例而不是Java中的泛型类型? - Why can we create new instances of a generic template and not of generic type in Java? 为什么我不能使用extend-type扩展Clojure的IFn? - Why can't I extend Clojure's IFn using extend-type? 为什么我不能使用泛型类型的实例,但是不能在外部使用呢? - Why can't I use instances of a generic type but can outside? 为泛型类型扩展 Object[] - Extend Object[] for generic type 为什么我们不能在非泛型类中使用泛型方法? - Why can't we have generic methods inside non-generic classes?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM