Java problem inheriting interface implementation when extending a class

Advertisements

I am struggling to get an interface implementation to be inherited in another class:

I have a generic class that requires compareTo to be implemented. The class is called GenericList and is implemented as:

public class GenericList<T extends Comparable<T>> {
    private T[] items;
    private int count;
    public GenericList() {
        items = (T[]) new Comparable[10];
        count = 0;
    }
}

I have a User class that implements compareTo:

public class User implements Comparable<User> {
    private String email;

    public User(String email) {
        this.email = email;
    }

    @Override
    public int compareTo(User o) {
        return (email.compareTo(o.email));

    }
}

I have no problem creating a GenericList of Users:

var users = new GenericList<User>();

If I create a class that extends User and try to create a generic list of that type, I get an error. I have created a class called Instructor:

public class Instructor extends User{
    public Instructor(String email){
        super(email);
    }
}

If I create a generic list using that class:

var instructors = new GenericList<Instructor>();

I get an error:

Type parameter 'com.martin.Instructor' is not within its bound; should implement 'java.lang.Comparable<com.martin.Instructor>'

Shouldn’t it use the inherited compareTo method?

I’ve tried lots of different ways but I can’t get GenericList to use an inherited class like this.

Thanks

>Solution :

public class GenericList<T extends Comparable<T>>

When you declare GenericList<Instructor>, then the above declaration replaces T with Instructor. So now it says that Instructor must extend (or implement, really) Comparable<Instructor>. The problem is that Instructor extends User which implements Comparable<User> but doesn’t implement Comparable<Instructor>.

So the problem is well before trying to find the inherited compareTo() method. One way to fix the immediate compiler error is to change the GenericList declaration:

public class GenericList<T extends Comparable<? super T>>

This uses a type capture on the Comparable interface.

Now fair warning, I have check that this change will compile here, but otherwise I have not tested it because your question doesn’t provide any usages of GenericList once you create it.

Leave a ReplyCancel reply