7

I don't think this is a duplicate of Check if a generic T implements an interface, but it may be(??).

So, I want to create a generic interface that only allows objects that implements two interfaces. Alike is a costum interface.

public interface AbstractSortedSimpleList<T extends Comparable<T>, Alike> {}

If I understand it correctly, Java now tries to create a generic interface AbstractSortedSimpleList<T,Alike>, which isnt exactly what I want to achieve. I want AbstractSortedSimpleList<T> where T has to implement both Comparable<T> and Alike.

Later, I want to make a new class

public class SortedSimpleList<T> implements AbstractSortedSimpleList<T> {}

The point here is to create a class SortedSimpleList<T> where T has to be implementing the aforementioned interfaces. But my code does not seem to work very well.

Community
  • 1
  • 1

2 Answers2

8

Use some generic bounds with the & notation

interface AbstractSortedSimpleList<T extends Comparable<T> & Alike> {

See the official Java tutorial on multiple bounds, here.

Sotirios Delimanolis
  • 274,122
  • 60
  • 696
  • 724
  • `public class SortedSimpleList implements AbstractSortedSimpleList {}` this now gives _Bound mismatch: The type T is not a valid substitute for the bounded parameter & Alike> of the type AbstractSortedSimpleList_ – Hans Petter Taugbøl Kragset Feb 18 '14 at 15:17
  • @hewo The use of `T` in `SortedSimpleTest` is a **new** type variable. You need to specify the bounds on it as well. Otherwise it doesn't fit the bounds that `AbstractSortedSimpleList` expects. – Sotirios Delimanolis Feb 18 '14 at 15:17
  • Edit: Yeah, I just put `T extends Comparable & Alike` in the wrong `<>` hehe. Thanks :) – Hans Petter Taugbøl Kragset Feb 18 '14 at 15:22
  • @hewo See Rohit's answer below (above). Using `T` in `SortedSimpleList` is declaring a new type variable. Using `T` in `extends AbstractSortedSimpleList` is using `T` as a type argument. That distinction is important when using bounds. – Sotirios Delimanolis Feb 18 '14 at 15:23
7

You can give multiple bounds to type parameter:

public interface AbstractSortedSimpleList<T extends Comparable<T> & Alike>

Then, your SortedSimpleList would be like:

class SortedSimpleList<T extends Comparable<T> & Alike> implements AbstractSortedSimpleList<T> {}

See JLS §4.4:

Every type variable declared as a type parameter has a bound. If no bound is declared for a type variable, Object is assumed. If a bound is declared, it consists of either:

  • a single type variable T, or

  • a class or interface type T possibly followed by interface types I1 & ... & In.

Note:

You can't have such multiple bounds for wildcards though. It's only for type parameters.

References:

Community
  • 1
  • 1
Rohit Jain
  • 209,639
  • 45
  • 409
  • 525