Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I make an interface instance method accept arguments of the same class only, really?

This SO discussion proposes the following idiom:

public interface IComparable<T extends IComparable<T>> {
    int compare(T t);
}

which then allows:

public class Foo implements IComparable<Foo> {
    public int compare(Foo foo) {
        return 0;
    }
}

However, this idiom allows more than just the above as the following code compiles as well:

class A implements IComparable<A> {
    public int compare(A a) {return 0;}
}

public class Foo implements IComparable<A> {

    public int compare(A a) {
        return 0;
    }
}

Therefore (unless I've misunderstood something) the original idiom doesn't really buy anything more compared to the far less dramatic:

public interface IComparesWith<T> {
    int compare(T t);
}

public class A implements IComparesWith<A> {
    public int compare(A a) {...}
}

So, is there a way to actually declare an interface such that whatever class declares to implement it has a method to compare with objects of its own class, without any loopholes such the one above?

I obviously could't post the above as a comment hence I created a new post.

like image 873
Marcus Junius Brutus Avatar asked Jan 12 '23 11:01

Marcus Junius Brutus


1 Answers

No, that sort of restriction is not possible with the generics as written. Your assessment seems correct to me.

like image 186
caskey Avatar answered Jan 31 '23 00:01

caskey