Question

I have a question regarding generic types in Java. Specifically, at present, I have some code similar to this:

public interface Foo {
   public <T> void bar(T[] list)
}

public class FooImpl implements Foo{
   @Override
   public <T extends Comparable<? super T>> void bar(T[] list) {
       ...
   }
}

The problem is, that the compiler now complaints, that I have not implemented the bar-method in my FooImpl class.

What I want is to put some extra restriction on the generic type, specifically that they should be comparable. But I don't want to put that restriction in my Foo interface, as all implementations does not need that restriction. Is this possible, and what should I do to fix it?

Thanks a lot in advance!

EDIT 1: Fixed typos Class --> class and Interface --> interface. But the return types are still void, not T, which is irrelevant, I suppose. My actual return type is a boolean.

EDIT 2: The actual code, as requested:

public interface SortedCriteria {

    public <E> boolean isSorted(E[] list);

}

public class AscendingCriteria implements SortedCriteria {

    @Override
    public <E extends Comparable<? super E>> boolean isSorted(E[] list) {
        int length = list.length;
        for (int i = 1; i < length; i++) {
            if (list[i].compareTo(list[i-1]) < 0) return false;
        }
        return true;
    }

}
Was it helpful?

Solution

What you want to do is rejected because it would completely break polymorphism. A caller having a Foo instance could have an instance of your subclass or an instance of any other subclass. And since the interface guarantees that the method can be called with any kind of array as argument, your subclass can't break this contract by limiting the kind of array it accepts (unless it does that at runtime, by checking the type of the array and by throwing an exception, of course).

This boils down to the Liskov substitution principle, which is the basis of polymorphism and OO.

But maybe what you actually want is to make Foo a generic type:

public interface Foo<T> {
    public void bar(T[] list);
}

public class FooImpl<T extends Comparable<? super T>> implements Foo<T> {
   @Override
   public void bar(T[] list) {
       ...
   }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top