1

I have a problem with understanding Comparable interface in Java. Here is a code:

public class test{
public class Example1 implements Comparable<Example1> {
    private int id;

    public Example1(int id) {
        this.id = id;
    }

    public int getId() {
        return this.id;
    }

    public void setId(int id) {
        this.id = id;
    }


    @Override
    public int compareTo(Example1 o) {
        if (id == o.getId())
            return 0;
        else if (id > o.getId())
            return 1;
        else
            return -1;
    }
}
public class Example2 extends Example1 implements Comparable<Example2> {
    public Example2(int id) {
        super(id);
    }
}

}

When I want to implement Comparable a second time I get an error java.lang.Comparable' cannot be inherited with different type arguments.

Why I'm not allowed to to implement a child class with Comparable interface? How can I resolve this problem? I will be very thankful for answer.

  • You can't declare a different comparable because all `Example1`s (and subclasses) already implement `Comparable`, and thus a subclass can't implement a different `Comparable` as well. It's the same reason you can't make a single class implement `Comparable` twice. – Andy Turner Apr 17 '21 at 11:24
  • @AndyTurner is there any way to resolve this? – Misha Solop Apr 17 '21 at 11:36
  • I am not sure, but try put T as Example 1 parameter and give it to comparable. When you extend Example1 then, give Example2 – DynoZ Apr 17 '21 at 11:39
  • public class A implements Comparable{} then public class B extends A – DynoZ Apr 17 '21 at 11:40
  • I agree that it’s a weird restriction of Java generics, but it’s a restriction. The explanation for it can be found in the way generics are implemented. – Ole V.V. Apr 17 '21 at 11:47
  • A tip: Paste your error message into your search engine. That will very often lead to both an explanation and a solution. – Ole V.V. Apr 17 '21 at 11:47

0 Answers0