Reputation: 165
I have a class Player with some fields:
String name;
Point position;
Action action;
The 'name' field is sort of a key, there cannot be 2 players with the same name. So it seems to me they are equals if the 'name' (probably case ignored) is the same. So do I use the String.equalsIgnoreCase(String) only or do I check the other fields as well?
1) Should I check more than the name field in the equals method of Player?
2) Should I throw an error in the equals method if the other fields are not the same?
3) And is it wise to check that one field only for subclasses, because even in subclasses the same name, indicates the same player, or should I choose another method for comparing this? Example:
class MovingPlayer extends Player{
Point destination;
So the 'name' field is still the key (something like an inter-subclass key).
Thanks in advance, Tjen
Upvotes: 3
Views: 160
Reputation: 24910
You should ask yourself the question -- is it possible for two objects with the same name property and two different position properties to exist in your application? If that is true, then you should implement the equals method to use all relevant fields.
You dont throw an error in the equals method. You return true or false.
Your subclasses can override the equals method. In that overridden method, you can check for superclas equals and only if they are equal, you continue with additional checking.
Upvotes: 2