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.
However, it can be achieved with interfaces, because the class can implement multiple interfaces. Note: To implement multiple interfaces, separate them with a comma (see example below).
Only generic classes can implement generic interfaces. Normal classes can't implement generic interfaces.
A class implementation of a method takes precedence over a default method. So, if the class already has the same method as an Interface, then the default method from the implemented Interface does not take effect. However, if two interfaces implement the same default method, then there is a conflict.
In interfaces, a class can implement more than one interface which can't be done through extends keyword.
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:
Use some generic bounds with the &
notation
interface AbstractSortedSimpleList<T extends Comparable<T> & Alike> {
See the official Java tutorial on multiple bounds, here.
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