Reputation: 2779
I have the following class structure:
public abstract class Generic<T extends SuperClass>
public class SuperGeneric<T extends SuperClass & SomeInterface>
extends Generic<T>
Now I want to make an instance of SuperGeneric
covering all possible classes. I tried it like this:
Generic<? extends SuperClass & SomeInterface> myGeneric
= new SuperGeneric<? extends SuperClass & SomeInterface>();
Now this doesn't seem to work.
On Generic
it gives the following error: Incorrect number of arguments for type Generic<T>; it cannot be parameterized with arguments <? extends SuperClass, SomeInterface>
.
And on the new SuperGeneric
I get a similar error: Incorrect number of arguments for type SuperGeneric<T>; it cannot be parameterized with arguments <? extends SuperClass, SomeInterface>
.
Any idea how to correctly create instances of this SuperGeneric
?
The idea is that I have 2 different classes that satisfy the extends SuperClass & SomeInterface
condition but those cannot be generalized by one type.
Upvotes: 3
Views: 512
Reputation: 6163
When you want to instantiate a generic class, you need to provide the concrete type. You said there are two classes that fulfill the constraint. Say these are Type1
and Type2
.
Then you should be able to do:
Generic<Type1> myGeneric1 = new SuperGeneric<Type1>();
and
Generic<Type2> myGeneric2 = new SuperGeneric<Type2>();
The wildcards are used only for declaration. They mean: You can put any type here (that fulfills the given constraints)
Upvotes: 2
Reputation: 15363
When you instantiate you need to provide a type for the compiler to fill in.
Upvotes: 2