tags:

views:

203

answers:

2
public abstract class MyAbs implements Comparable<MyAbs>

This would work but then I would be able to compare class A and B with each other if they both extend MyAbs. What I want to accomplish however is the exact opposite.

So does anyone know a way to get the generic type to be the own class? Seemed like such a simple thing at first...

Edit:

To explain it a little further with an example. Say you have an abstract class animals, then you extend it with Dogs and ants.

I wouldn't want to compare ants with Dogs but I however would want to compare one dog with another. The dog might have a variable saying what color it is and that is what I want to use in the compareTo method. However when it comes to ants I would rather want to compare ant's size than their color.

Hope that clears it up. Could possibly be a design flaw however.

+1  A: 

Simply implement Comparable<MyAbs> on class B, which if I interpret your question correctly, extends MyAbs. That way, objects of class B can be compared with any objects whose classes extend MyAbs, but not vice versa. However, if what you want is to have the type parameter reflect the concrete class' type, then you should probably pass Comparable a new type parameter.

I.E.:

public abstract class MyAbs<T> implements Comparable<T extends MyAbs>

But this of course has the disadvantage that now your concrete classes need to change their definition to

public class ConcreteClass extends MyAbs<ConcreteClass>

Looks kindof nasty, but it should work. It's probably better to implement Comparable separately on each concrete class.

firebird84
Syntax is a bit broken there.
Tom Hawtin - tackline
How so? I left out the braces but other than that it should be fine.
firebird84
A: 

Most straightforward would be:

public abstract class MyAbs<T> implements Comparable<T>

Perhaps more usefully, you go Enum style:

public abstract class MyAbs<THIS extends MyAbs<THIS>> implements Comparable<THIS>

You may possibly be able to ignore the issue:

public abstract class MyAbs

An external Comparator feels more natural to me (that is to say, don't have a natural order).

Tom Hawtin - tackline
That Enum thing looks interesting, haven't really learned to use enum yet so gonna look into how that one functions.But I'm probably just gonna implement comparable for each subclass instead.
dege