[英]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
)。
對於第二個實現,您可以將Cat
與Dog
進行比較,但仍然可以true
,因為兩者都是Animal
實例並具有相同數量的腿。
如果沒有Animal
類的子類,它們的行為會相同,因為在這種情況下,如果other instanceof Animal
為true,
getClass()== other.getClass() is also
為true,
。
PS,第二個片段有一個拼寫錯誤,因為你重新聲明了other
變量:
Animal other = (Animal) other;
return this.numLegs == other.numLegs;
您可能打算使用不同的變量名稱。
他們對Animal
子類沒有做同樣的事情; 說,如果你有一個類Dog
延長Animal
,和實例dog
,叫animal.equals(dog)
將返回false
與第一個版本,並true
與第二。
他們是不同的:
情況1:如果實例屬於同一個類,如Cow extends Animal
和Cat extends Animal
則此檢查將始終返回true
。
情況2:在這種情況下,如果兩者都是Animal的實例並具有相同數量的腿 - 返回true。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.