2

I have an interface A, and wish to write an generic interface B such that any T that implements B must also have implemented both A and Comparable. A is not currently a generic interface.

Is this possible? Do I need to make A generic? I had hoped to be able to write something like:

public interface B<T implements Comparable, A> {}

But this does not seem to work... Can anyone point me in the right direction?

I do not believe this is a duplicate of the question that has been linked.

beoliver
  • 5,579
  • 5
  • 36
  • 72

2 Answers2

1

Just make B to extend A and Comparable.

public interface A {
    public void methodA();
}

public interface B<T> extends A, Comparable<T> {
    public T methodB();
}

public class BImpl<T> implements B<T> {
    @Override
    public T methodB() {
        return null;
    }

    @Override
    public void methodA() {

    }

    @Override
    public int compareTo(T o) {
        return 0;
    }
}
Aleksander Mielczarek
  • 2,787
  • 1
  • 24
  • 43
1

What you are looking for here are multi-bounded generic types:

public interface B<T extends A & Comparable> {}

Note that if either of the bounded types is a class instead of an interface, it has to be the first bound defined after extends. Also, you cannot use multi-bounded generic types on more than one class(since there is no multiple-inheritance in Java)

Clashsoft
  • 11,553
  • 5
  • 40
  • 79