Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can you define a generic bound that both has lower and upper bounds?

Tags:

java

generics

Is it possible to define a generic bound that:

  • implements an interface SomeInterface
  • is a superclass of some class MyClass

Something like:

Collection<? extends SomeInterface & super MyClass> c; // doesn't compile
like image 814
Bohemian Avatar asked Jan 02 '13 20:01

Bohemian


People also ask

What is upper bound and lower bound in generics?

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.

Is it possible to declared a multiple bounded type parameter?

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.

How are bounds used with generics?

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.


1 Answers

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 
like image 186
jtahlborn Avatar answered Sep 30 '22 19:09

jtahlborn