St.Antario
St.Antario

Reputation: 27375

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?

Upvotes: 1

Views: 74

Answers (1)

Vincent van der Weele
Vincent van der Weele

Reputation: 13177

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 x = new MyExtendedClass();

There is no way to tell what T should be in that case!

Upvotes: 6

Related Questions