dai
/**
*
*/
/**
* @author laishengfeng
* @2014-8-20
* @TODO equals方法的重写
*/
public class Citizen {
String id; // 身份证号
String name; // 名字
int age; // 年龄
String sex; // 性别
// 用构造方法对成员变量进行初始化
public Citizen(String theId, String theName, int theAge, String theSex) {
this.id = theId;
this.name = theName;
this.age = theAge;
this.sex = theSex;
}
// 重写equals()方法
public boolean equals(Object obj) {
// 首先需要判断obj是否为null, 如果为null,返回false
if (obj == null) {
return false;
}
// 判断测试的是否为同一个对象,
// 如果是同一个对象,无庸置疑,它应该返回true
if (this == obj) {
return true;
}
// 判断它们的类型是否相等,
// 如果不相等,则肯定返回false
if (this.getClass() != obj.getClass()) {
return false;
}
// 将参数中传入的对象造型为Citizen类型
Citizen c = (Citizen) obj;
// 比较两个对象的所有属性是否一样,就可以得出这两个对象是否相等
if ((this.id) == (c.id) && (this.name).equals(c.name)
&& (this.age) == (c.age) && (this.sex).equals(c.sex)) {
return true;
}else {
return false;
}
}
}
上面是重写的具体过程
然后 用一个测试类 来进行验证
/**
*
*/
/**
* @author laishengfeng
* @2014-8-20
* @TODO 测试Citizen类
*/
public class TestCitizen
{
public static void main(String[] args)
{
Citizen c1 = new Citizen("id00001","zhangsan",20,"男");
Citizen c2 = new Citizen("id00001","zhangsan",20,"男");
System.out.println(c1.equals(c2));
}
}