Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

implementing Comparable in an interface

I am calling a specific class using only its interface. The problem is, the class itself implements Comparable, but because I am referring to the class via a different interface, the compiler does not know it implements Comparable. I'm sure there is an easy solution to this... but I just can't think of it right now.

like image 827
Ben B. Avatar asked Dec 22 '22 22:12

Ben B.


2 Answers

This seems odd to me... if you have main like the following, you can make it work with the Parent interface and Child classes below... but there is an oddity in that you could try to compare a ChildA to a ChildB which probably doesn't make sense to do.

Maybe if you gave us a hint at what the classes/interface are doing we could give a better answer.

public class Main
{
    public static void main(final String[] argv)
    {
        Parent x;
        Parent y;

        x = new ChildA();
        y = new ChildA();
        x.compareTo(y);
    }
}

abstract interface Parent
    extends Comparable<Parent>
{
}

class ChildA
    implements Parent
{
    public int compareTo(Parent o)
    {
        throw new UnsupportedOperationException("Not supported yet.");
    }
}

class ChildB
    implements Parent
{
    public int compareTo(Parent o)
    {
        throw new UnsupportedOperationException("Not supported yet.");
    }
}
like image 35
TofuBeer Avatar answered Jan 14 '23 12:01

TofuBeer


Will everything that implements the interface also implement Comparable<T>? If so, I suggest you just make the interface extend Comparable<T>.

Otherwise, you could just cast to Comparable<T> if you happen to know that in this case it will work. Of course, that loses some compile-time type safety, but that's the nature of the beast.

like image 51
Jon Skeet Avatar answered Jan 14 '23 13:01

Jon Skeet