***摘自Java核心技术 卷I***
class A {
private String name;
private int age;
A(String name, int age) {
this.name = name;
this.age = age;
}
/**
* 重写equals方法,如果在子类中重新定义equals,就要在其中包含调用super.equals(other)
*
*
* @param otherObject
* @return
*/
@Override
public boolean equals(Object otherObject) { //1、显示参数命名为otherObject,稍微需将其转换成另一个叫做other的变量
if (this == otherObject) { //2、检测this与otherObject是否引用同一个对象 这是经常采用的方式,因为其代价比逐个比较类
return true; // 中的域代价要小得多。
}
if (otherObject == null) { //3、检测otherObject是否为null 很有必要的检测
return false;
}
if (getClass() != otherObject.getClass()) { //4、比较this与otherObject是否属于同一个类。如果equals的语义在每个子类中都有所改变,就使
return false; // 用getClass()检测。如果所有的子类都拥有统一的语义,就使用 instanceof 检测:
} // if(!(otherObject instanceof ClassName)) return false;
A other = (A) otherObject; //5、将otherObject转换为相应的类类型变量 ClassName other = (ClassName) otherObject
return name.equals(other.name) //6、逐个对对象中的域进行比较,如果所有的域都匹配,返回true;否则返回false。
&& (age == other.age);
}
}
instanceof:比较的是继承关系或者实现关系的类类型,子类对象或者实现类对象放在前面。
instanceof是Java的一个二元操作符,作用是测试它左边的对象是否是它右边的类的实例,返回boolean类型的数据。
getClass(): 比较任何类的类型。