Is it possible to define a generic bound that:
SomeInterface
MyClass
Something like:
Collection<? extends SomeInterface & super MyClass> c; // doesn't compile
According to the spec , the answer would be no (you can have super
or extends
, but not both):
TypeArguments: \n < TypeArgumentList > \n\nTypeArgumentList: \n TypeArgument \n TypeArgumentList , TypeArgument \n\nTypeArgument: \n ReferenceType \n Wildcard \n\nWildcard: \n ? WildcardBounds opt \n\nWildcardBounds: \n extends ReferenceType \n super ReferenceType
You cannot use generic type ( T
in your case) with bounds when declaring a variable.
It should be either a wildcard ( ?
), or just use the full generic type of the class.
Eg
// Here only extends is allowed
class My< T extends SomeInterface >
{
// If using T, then no bounds are allowed
private Collection<T> var1;
private Collection< ? extends SomeInterface > var2;
// Cannot have extends and super on the same wildcard declaration
private Collection< ? super MyClass > var3;
// You can use T as a bound for wildcard
private Collection< ? super T > var4;
private Collection< ? extends T > var5;
}
In some cases, you may tighten the declaration by adding extra generic parameter to a class (or method) and adding a bound on that particular parameter:
class My <
T extends MyClass< I >,
I extends SomeInterface
>
{
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.