Java Abstract Class Implementing an Interface with Generics

Cem picture Cem · Aug 29, 2010 · Viewed 29.3k times · Source

I am trying to define an abstract class implementing Comparable. When I define the class with following definition:

public abstract class MyClass implements Comparable <MyClass>

subclasses have to implement compareTo(MyClass object). Instead, I want every subclass to implement compareTo(SubClass object), accepting an object of its own type. When I try to define the abstract class with something like:

public abstract class MyClass implements Comparable <? extends MyClass>

It complains that "A supertype may not specify any wildcard."

Is there a solution?

Answer

whiskeysierra picture whiskeysierra · Aug 29, 2010

It's a little too verbose in my opinion, but works:

public abstract class MyClass<T extends MyClass<T>> implements Comparable<T> {

}

public class SubClass extends MyClass<SubClass> {

    @Override
    public int compareTo(SubClass o) {
        // TODO Auto-generated method stub
        return 0;
    }

}