I know it's possible to add multiple constraints to a Generic class definition, e.g.:
class Example<I extends Object & Comparable<Object>>{}
But I want a generic (MyGeneric
) that takes another generic (SomeGeneric<T>
) as its type parameter, and to constrain the type parameter (T
) of that generic (e.g. T extends SomeClass
).
Important, I need to know the types of both SomeGeneric
and SomeClass
from inside the class (G
and T
need to both be bound). For example, imagine something like this:
class MyGeneric<G extends SomeGeneric<T>, T extends SomeClass>
{
public G returnSomeGenericImpl(){}
public T returnSomeClassImpl(){}
}
Question: The above works, but I would prefer if my class had only one type parameter, to make life easier for implementers of my class. Is there a way of doing this?
Something like this would be nice (but this particular code is incorrect):
class MyGeneric<G extends SomeGeneric<T extends SomeClass>>
{
public G returnSomeGenericImpl(){}
public T returnSomeClassImpl(){}
}
If I wasn't clear, I'll gladly try to clarify my intent.
Multiple parametersYou can also use more than one type parameter in generics in Java, you just need to pass specify another type parameter in the angle brackets separated by comma.
There can be more than one constraint associated with a type parameter. When this is the case, use a comma-separated list of constraints. In this list, the first constraint must be class or struct or the base class.
A Generic class can have muliple type parameters.
Generic Classes As with generic methods, the type parameter section of a generic class can have one or more type parameters separated by commas. These classes are known as parameterized classes or parameterized types because they accept one or more parameters.
It looks impossible to achieve.
After reducing your type definition by one order by removing one type variable and trying to define it,
class G extends SomeGeneric<T extends SomeClass>{}
does not compile because the type parameter T is not bound with respect to an already defined type parameter. But, this works -
class G<T extends SomeClass> extends SomeGeneric<T>{}
So, I infer that the only way of parameterizing with two types is by declaring them up front.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With