Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java generic classes, how to make an instance

Tags:

java

generics

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.

like image 319
Steven Roose Avatar asked Jan 28 '26 12:01

Steven Roose


2 Answers

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)

like image 161
hage Avatar answered Jan 31 '26 00:01

hage


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

like image 33
nsfyn55 Avatar answered Jan 31 '26 01:01

nsfyn55