為什么我這里兩對(duì)象不同類型相同屬性的值用equals()方法判斷是相同的呢?
public class Phone {
int screen=1;
public float a() {
float screen=1;
return screen;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Phone other = (Phone) obj;
if (screen != other.screen)
return false;
return true;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Phone phone1=new Phone();
phone1.screen=1;
Phone phone2=new Phone();
phone2.a();
if(phone1.equals(phone2))
System.err.println("兩對(duì)象相同? phone1.screen:"+phone1.screen+"? phone2.a():"+phone2.a());
else
System.out.println("兩對(duì)象不相同? phone1.screen:"+phone1.screen+"? phone2.a():"+phone2.a());
}
}
視頻里老師說equals()方法里判斷類型不同會(huì)返回false? 但我這段代碼不同類型也返回true? 我哪里理解錯(cuò)了呢?? ?
2018-08-20
哦哦 我明白了? 我兩對(duì)象比較錯(cuò)了?if(phone1.equals(phone2))這里應(yīng)該是?if(phone1.equals(phone2.a()))
我的想法是用equals()方法比較相同屬性的成員變量與局部變量?
經(jīng)過測(cè)試 兩對(duì)象確實(shí)是不同的 即使都是int類型也是不同的
2018-08-20
不都是Phone類型嗎,親?