3

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.

2 Answers 2

2

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)

Sign up to request clarification or add additional context in comments.

2 Comments

So where are wildcards used then? In method arguments and return-types?
@stevenroose see my last sentence
2

When you instantiate you need to provide a type for the compiler to fill in.

5 Comments

So where are wildcards used then? In method arguments and return-types?
The wildcards describe what T can be. But you actually need to provide something for T.
You are conflating Class Literals and other Generics features.
@nsfyn55 I find Java syntax confusing too. Whereas in C# you put the type constraints on separate clause(in where); in Java you put the type constraint declaration inside the generics declaration (Generic<T extends ClassNameHere>), hence your confusion on how to instantiate it. Having said that, when you instantiate(be it Java or C#), they are very simple, same syntax(i.e. Generic<SomeClass> x = new SuperGeneric<SomeClass>()), see my comparison at anicehumble.com/2012/05/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.