基本数据类型使用==比较的是数据
* 引用数据类型==比较的地址
* 引用数据类的内容的比较要使用equals
* 因为object的equals比较的还是引用,无法满足子类的要求,需要子类重写
在Animal类中将eaquls进行重写
public boolean equals(Object obj) {
//如果obj是null,直接返回false
if (obj == null) {
return false;
}
//如果两个引用变量指向同一个对象,直接返回true
if (this == obj) {
return true;
}
Animal other = (Animal) obj;
//如果color和age都相等,返回ture
if (this.color == other.color && this.age == other.age) {
return true;
}else {
return false;
}
}
在Dog类中将equals进行重写
public boolean equals(Object obj) {
boolean flag = super.equals(obj);
if (flag) {
//在比较nickName和type
Dog other = (Dog) obj;
// if (this.nickName == other.nickName && this.type == other.type) {
if (this.nickName.equals(other.nickName) && this.type.equals(other.type)) {
return true;
} else {
return false;
}
}else
{
return false;
}
}
这里 if (this.nickName.equals(other.nickName) && this.type.equals(other.type))
中的“equals”,点击ctrl+左击查看其代码段