开发者

Can I use only the key field to check equals? And can I use equals through subclasses?

开发者 https://www.devze.com 2023-03-22 23:34 出处:网络
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 eq

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.equalsI开发者_运维问答gnoreCase(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


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

  2. You dont throw an error in the equals method. You return true or false.

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

0

精彩评论

暂无评论...
验证码 换一张
取 消