Tuesday, 19 April 2011

Using multiple bounds in generics

The <A extends B> syntax applies even if B is an interface because 1) it doesn't matter operationally if B is a class or an interface and 2) if B is a type parameter, the compiler doesn't know a priori whether it is a class or an interface.  
Since Java allows multiple inheritance in the form of implementing multiple interfaces, it is possible that multiple bounds are necessary to specify a type parameter.    To express this situation, one uses the following syntax:
<T extends A & B & C & ...>
For instance:
  interface A {
...
}

interface B {
...
}

class MultiBounds<T extends A & B> {
...
}

No comments:

Post a Comment