Suppose I have an abstract Superclass named that is defined like this:
public abstract class Member implements Comparable<Member>
And then I have two Subclasses of Member
, defined like this:
public class Coach extends Member
public class Player extends Member
Then, I have a list of Member
, which means it contains both Coach
and Player
.
I need to sort this list, in which a coach always comes first and then come the players sorted by an identification number.
I need to implement the compareTo
method to do this. But how do I proceed, knowing that I can't implement the method in the superclass Member
, since the identification number is a property of Player
and Coach
doesn't have it?
I hope I've been clear on the problem.
You've got a couple of options here:
compareTo
method on Member
and write a compator which will check whether member object is the instance of Coach (then it will be always before other Member
object). In this solution, however you assume however that base class will know about it's implementors which might be considered a bad design, as once you start introducing more implementing classes (i.e. Referee
, Technical Assistant
etc.) you'll need to change the method every time, and might end up with something really complicated.
On the other hand though you've got the full ordering control in one place, which is easier to test and reason about than...
getOrderingIndicator()
abtract method which you'll implement in both Player
(assign identification number) and Coach
(assign 0 or some other value lower than allowed player identification number) and use this abstract method in the compareTo
method in Member
class.In this solution you'll guarantee that whatever implementations of Member
base class there are in the future, they will be correctly ordered.
All in all though, I'd strongly suggest implementing the compareTo
on the member level, since it's the Member
objects you're comparing.