javainheritancepolymorphismcompareto

Sort Superclass list of objects that are Subclasses of the Superclass


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.


Solution

  • You've got a couple of options here:

    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...

    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.