繁体   English   中英

覆盖从Object继承的equals方法

[英]Overriding the equals method that is inherited from Object

我被赋予了重写java中的equals方法的任务,我想知道我提供的两个例子是否会完成同样的事情。 如果是这样,他们之间有什么区别。

public class Animal {

    private int numLegs;

    public Animal(int legs) {
        numLegs = legs;
    }

    public boolean equals(Object other) {
        if(other == null) return false;
        if(getClass() != other.getClass()) return false;

        return this.numLegs == ((Animal)other).numLegs;
}
public class Animal {

    private int numLegs;

    public Animal(int legs) {
        numLegs = legs;
    }

    public boolean equals(Object other) {
        //check if other is null first
        if(other == null) return false;
        //Check if other is an instance of Animal or not 
        if(!(other instanceof Animal)) return false;
        //// typecast other to Animal so that we can compare data members
        Animal other = (Animal) other;
        return this.numLegs == other.numLegs;
    }

她们不一样。

对于第一个实现,如果两个比较的实例属于同一个类,则只能返回true (例如,如果两个都是Cat实例,假设Cat扩展为Animal )。

对于第二个实现,您可以将CatDog进行比较,但仍然可以true ,因为两者都是Animal实例并具有相同数量的腿。

如果没有Animal类的子类,它们的行为会相同,因为在这种情况下,如果other instanceof Animaltrue, getClass()== other.getClass() is alsotrue,

PS,第二个片段有一个拼写错误,因为你重新声明了other变量:

Animal other = (Animal) other;
return this.numLegs == other.numLegs;

您可能打算使用不同的变量名称。

他们对Animal子类没有做同样的事情; 说,如果你有一个类Dog延长Animal ,和实例dog ,叫animal.equals(dog)将返回false与第一个版本,并true与第二。

他们是不同的:

情况1:如果实例属于同一个类,如Cow extends AnimalCat extends Animal则此检查将始终返回true

情况2:在这种情况下,如果两者都是Animal的实例并具有相同数量的腿 - 返回true。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM