2011-09-01 123 views
1

我需要创建一个名为EOHoverFrog的HoverFrog的子类。 EhooverFrog的实例不同于HoverFrog的实例,因为如果EhooverFrog的两个实例的位置和高度相同,无论其颜色如何,均认为这两个实例相同。实例方法equals()

为此,我需要为EOHoverFrog编写一个实例方法equals(),该方法将覆盖从Object继承的equals()方法。该方法应该接受任何类的参数。如果参数的类与接收方的类不同,则该方法应简单地返回false,否则应测试接收方和参数的相等性。

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

请你能告诉我,我到底对不对?

+0

考虑到这个代码甚至不会编译,我要去......不。 –

回答

4
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 
} 
+1

注意:'instanceof'不检查'obj'类是否是EHoverFrog!对于EHoverFrog的任何子类,它也会返回true,但问题要求“参数的类与接收者的类不一样” –

1

这似乎不正确。

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

实现的equals方法的一个好方法是:

1)确保传递的其他对象,obj你的情况,是不是零和正确的类(或类)。在你的情况下,EOHoverFrogHoverFrog实例可以相等吗?

2)做你的比较,像

//假设两个高度和位置是在基CALSS

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

3)现在,你是在适当的位置,以检查平等

return isHeightEqual && isPositionEqual; 
0

首先,阅读this以了解每个equals()方法必须如何表现。其次,如果您重写equals()方法,那么在方法之前添加@Override注释是个好习惯。

要学习示例,您可以学习很多equals()实现here