开发者

instance method equals()

I need to create a subclass of HoverFrog called EOHoverFrog. Instances of EOHoverFrog differ from instances of HoverFrog in that two instances of EOHoverFrog are considered equal if their position and height are the same, regardless of their colour.

To do this, I need to write an instance method equals() for EOHoverFrog that overrides the equals() method inherited from Object. The method should accept an argument of any class. If the class of the argument is not the same as the cl开发者_开发问答ass of the receiver, the method should simply return false, otherwise it should test the equality of the receiver and the argument.

public boolean equals(Object obj)
{
   Frog.getClass().getHeight();
   HeightOfFrog height = (HeightOfFrog) obj;
   return (this.getPosition() == frog.getPosition());
  }

please could you tell me whether I'm correct?


public boolean equals(Object obj) {
    // my first (incorrect) attempt, read Carlos Heuberger's comment below
    // if (!(obj instanceof EOHoverFrog))
    //    return false;
    if (obj == null)
        return false;
    if (getClass() != obj.getClass())
        return false;
    // now we know obj is EOHoverFrog and non-null
    // here check the equality for the position and height and return
    // false if you have any differences, otherwise return true
}


that doesn't seem correct.

public boolean equals(Object obj)
{
   Frog.getClass().getHeight(); // you arent assigning this to anything, and class probably
                                // doesn't have a getHeightMethod()

   HeightOfFrog height = (HeightOfFrog) obj; // obj should be an EOHoverFrog; you should
                                             // return false above this if obj is null or the 
                                             // wrong class

   return (this.getPosition() == frog.getPosition()); // what is frog?  It is not defined
                                                      // in your example

   // you are not comparing heights anywhere.
}

A good way to implement an equals method is:

1) Make sure the other object passed in, obj in your case, is not null and the right class (or classes). In your case, can EOHoverFrog and HoverFrog instances be equal?

2) do your comparisons, something like

// assuming both height and position are on the base calss

var isHeightEqual = this.getHeight() == ((HoverFrog)obj).getHeight();
var isPositionEqual = this.getPosition() == ((HoverFrog)obj).getPosition(); 

3) now you are in position to check equality

return isHeightEqual && isPositionEqual;


First of all, read this to understand how each equals() method must behave.

Second, if you overrides the equals() method, then it's good practice to add @Override annotation before method.

To learn by examples, you can study a lot of equals() implementations here.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜