Is it possible to define a generic bound that:
SomeInterface
MyClass
Something like:
Collection<? extends SomeInterface & super MyClass> c; // doesn't compile
Upper-bound is when you specify (? extends Field) means argument can be any Field or subclass of Field. Lower-bound is when you specify (? super Field) means argument can be any Field or superclass of Field. Try following code: Uncomment the code and check if any error comes.
Multiple BoundsBounded type parameters can be used with methods as well as classes and interfaces. Java Generics supports multiple bounds also, i.e., In this case, A can be an interface or class. If A is class, then B and C should be interfaces. We can't have more than one class in multiple bounds.
Whenever you want to restrict the type parameter to subtypes of a particular class you can use the bounded type parameter. If you just specify a type (class) as bounded parameter, only sub types of that particular class are accepted by the current generic class. These are known as bounded-types in generics in Java.
According to the spec, the answer would be no (you can have super
or extends
, but not both):
TypeArguments: < TypeArgumentList > TypeArgumentList: TypeArgument TypeArgumentList , TypeArgument TypeArgument: ReferenceType Wildcard Wildcard: ? WildcardBoundsopt WildcardBounds: extends ReferenceType super ReferenceType
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