我需要创建一个名为EOHoverFrog的HoverFrog子类。 EOHoverFrog的实例与HoverFrog的实例不同之处在于,如果EOHoverFrog的两个实例的位置和高度相同,则认为它们是相等的,无论其颜色如何。
为此,我需要为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 :(得分: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
)不为null且为正确的类(或类)。在您的情况下,EOHoverFrog
和HoverFrog
实例可以相等吗?
2)进行比较,比如
//假设身高和位置都在基础上
var isHeightEqual = this.getHeight() == ((HoverFrog)obj).getHeight();
var isPositionEqual = this.getPosition() == ((HoverFrog)obj).getPosition();
3)现在你有能力检查平等
return isHeightEqual && isPositionEqual;
答案 2 :(得分:0)