所以场景如下:
class Feline
{
String name;
int age;
equals(Object obj) {...}
hashCode(){...}
}
class Cat extends Feline
{
int teeth;
hashCode(){...}
equals(Object obj)
{
if (!super.equals(obj))
{
return false; //If I don't want this should I use
}
...
}
}
Run Code Online (Sandbox Code Playgroud)
问题实际上这种继承是正确的,但对于程序来说,它不一定是真的.我对此的想法Cat实际上应该由一个Feline对象组成.问题是,我应该采取以下哪种方法?
编辑
这是Eclipse的实现,默认等于/ hashcode.可能是equals的实现并不是最准确的方法.
在继承面前进行Ohoh平等检查.这非常难以正确而且需要很长时间来描述.
正确的解决方案并不像人们想象的那样直截了当,所以请仔细阅读 - 这应该清除所有问题.如果不是随便再问:)
编辑:所以作为上述链接的简短摘要:一个相等方法应该满足以下属性:
为了保证这一点,我们需要指定另一种方法:public boolean canEqual(Object other).如果另一个对象是(重新)定义canEqual的类的实例,则此方法应返回true,否则返回false.
换句话说,如果我们覆盖equal()自己,则必须始终覆盖该方法.实现本身是微不足道的,一个简短的例子:
class Foo {
public boolean canEqual(Object other) {
return other instanceof Foo;
}
// equals implementation, etc.
}
Run Code Online (Sandbox Code Playgroud)
equals方法本身必须始终首先检查给定对象是否可以等于自身,例如,某些东西other.canEqual(this) && restOfComparison.
扩展上述Foo的类的简短示例:
class Bar extends Foo {
public boolean equals(Object other) {
if (other instanceof Bar) {
Bar that = (Bar)other;
return that.canEqual(this) && otherStuff;
}
return false;
}
public boolean canEqual(Object other) {
return other instanceof Bar;
}
}
Run Code Online (Sandbox Code Playgroud)