第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號(hào)安全,請(qǐng)及時(shí)綁定郵箱和手機(jī)立即綁定

怎么比較兩個(gè)不同子類的值是否相等?

package?com.imooc;

public?class?Animal?{
????public?String?name;
????public?int?age;

????@Override
????public?boolean?equals(Object?obj)?{
????????if?(this?==?obj)
????????????return?true;
????????if?(obj?==?null)
????????????return?false;
????????if?(getClass()?!=?obj.getClass())
????????????return?false;
????????Animal?other?=?(Animal)?obj;
????????if?(age?!=?other.age)
????????????return?false;
????????return?true;
????}
}
package?com.imooc;

public?class?Dog?extends?Animal?{

}
package?com.imooc;

public?class?Cat?extends?Animal?{

}
package?com.imooc;

public?class?Initial?{
????public?static?void?main(String[]?args)?{

????????Dog?dog?=?new?Dog();
????????Dog?dog2=new?Dog();
????????Cat?cat?=?new?Cat();
????????dog.age=1;
????????dog2.age=1;
????????cat.age=1;

????????if(dog.equals(dog2)){
????????????System.out.println("dog和dog2的age相同");
????????}else{
????????????System.out.println("dog和dog2的age不同");
????????}

????????if(dog.equals(cat)){
????????????System.out.println("dog和cat的age相同");
????????}else{
????????????System.out.println("dog和cat的age不同");
????????}
????}
}

結(jié)果為dog和dog2的age相同,dog和cat的age不同

為什么new同一個(gè)子類時(shí),equals可以比較屬性值,而new不同子類時(shí),不能比較屬性值,怎么修改才能比較不同子類的屬性值

謝謝


正在回答

11 回答

package?com.imooc;

public?class?Animal?{
????public?String?name;
????public?int?age;
}
package?com.imooc;

public?class?Dog?extends?Animal?{
????String?name="狗";
????int?age=1;
}
package?com.imooc;

public?class?Cat?extends?Animal?{
????String?name="狗";
????int?age=2;
}
package?com.imooc;
import?java.util.Scanner;

public?class?Initial?{
????public?static?void?main(String[]?args)?{
????????Scanner?input=new?Scanner(System.in);
????????System.out.println("請(qǐng)輸入動(dòng)物名");
????????String?choose1=input.next();
????????Animal[]?animal={new?Dog(),new?Cat()};
????????for(int?i=0;i<animal.length;i++){
????????????if(choose1==animal[i].name){
????????????System.out.println("已找到"+choose1);
????????????}else?if(i==animal.length-1){
????????????????System.out.println("未找到"+choose1);
????????????}
????????}
????????System.out.println("\n請(qǐng)輸入1或2");
????????int?choose2=input.nextInt();
????????for(int?n=0;n<animal.length;n++){
????????????if(choose2==animal[n].age){
????????????System.out.println("已找到"+choose2);
????????????}else?if(n==animal.length-1){
????????????????System.out.println("未找到"+choose2);
????????????}
????????}
????????input.close();
????}
}


0 回復(fù) 有任何疑惑可以回復(fù)我~
#1

qq_文_17

回復(fù)了~
2016-04-08 回復(fù) 有任何疑惑可以回復(fù)我~
首頁上一頁12下一頁尾頁

舉報(bào)

0/150
提交
取消

怎么比較兩個(gè)不同子類的值是否相等?

我要回答 關(guān)注問題
微信客服

購(gòu)課補(bǔ)貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動(dòng)學(xué)習(xí)伙伴

公眾號(hào)

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號(hào)