簡體   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