Sign in to follow this  
bilsa

[java] Comparable interface

Recommended Posts

Hi again, I have stumbled upon an issue iäve never really thought much about. I'm having a class structure like this: class A implements Comparable<A> { } class C extends A implements Comparable<C> { } Which apparently is not allowed :( Currently I need to use the old non generic Comparable interface, which forces me to use the "instanceof" operator. Is there any other sollution to my problem?

Share this post


Link to post
Share on other sites
It depends on what you are trying to do. With C extending A also C implements Comparable<A>, and hence it is allowed to compare any derivative of A with A. Adding "C implements Comparable<C>" isn't needed in this case. Then the implementation may but often need not use the instanceof operator, since comparing with A is normally restricted to functionality already belonging to A.

If, on the other hand, you effectively want a class like

class A {
public int compareTo(A a) {...};
}
class C extends A {
public int compareTo(A a) {...};
public int compareTo(C c) {...};
}

then you cannot implement 2 Comparables, right you are. However, for what purpose do you need such a construct? Maybe a better way is out there, but due to lack of knowledge of the intentional purpose I can't figure one out.

Share this post


Link to post
Share on other sites
To clarify my previous post, notice please that Java doesn't dispatch overloaded function calls from runtime types! I.e. it doesn't look at runtime whether an instance is of type A or else C, and hence invokes the one or the other method. Instead, it invokes the best match considering the type known at compile time. Hence, although if you have both C.compareTo(A) and C.compareTo(C) implemented, you cannot be sure that C.compareTo(A) is never invoked with an instance of C (although you can be sure that C.compareTo(C) is never invoked with an instance of A, of course).

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this