[java] Comparable interface
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?
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
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.
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.
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).
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement