编写Doctor类{name,age,job,gender,sal},相应的getter()和setter()方法,五个参数的构造器重写父类的equals()方法:public boolean equals(Object obj),并判断测试类中创建的两个对象是否相等,相等就是判断属性是否相同。
public class Doctor {
private String name;
private int age;
private String job;
private String gender;//性别
private double sal;
//五个参数构造器
public Doctor(String name, int age, String job, String gender, double sal) {
this.name = name;
this.age = age;
this.job = job;
this.gender = gender;
this.sal = sal;
}
//重写父类Object的equals()方法: public boolean equals(Object obj)
//并判断测试类中创建的两个对象是否相等,相等就是判断属性是否相同。
public boolean equals(Object obj){
//1、要判断属性是否相同,那必须是同一个运行类型才能判断,所以先判断是否是是同一个运行类型
if (this == obj){
return true;//如果这两个是同一个运行类型而且相同的话肯定就相等
}
//2、当两个不是同一个运行类型的时候,先判断是否obj是否是Doctor类型或者Doctor的子类
if (!(obj instanceof Doctor)){//建议判断先先使用假条件时,现在则不是,不是就不能互相比较,所以直接false
return false;
}
//3、obj的运行类型是Doctor类型或者Doctor的子类时,将其 向下转型 去判断其属性是否相同
Doctor doctor = (Doctor) obj;
return this.name.equals(doctor.name) && this.age== doctor.age && this.gender.equals(doctor.gender)
&& this.job.equals(doctor.job) && this.sal==doctor.sal;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getJob() {
return job;
}
public void setJob(String job) {
this.job = job;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public double getSal() {
return sal;
}
public void setSal(double sal) {
this.sal = sal;
}
}
//测试类:
public class Test10 {
public static void main(String[] args) {
Doctor doctor1 = new Doctor("jake", 21, "teacher", "man", 3000);
Doctor doctor2 = new Doctor("jake", 21, "teacher", "man", 3000);
Doctor doctor3 = new Doctor("jake", 20, "teacher", "man", 3000);
System.out.println(doctor1.equals(doctor2));
System.out.println(doctor1.equals(doctor3));
}
}
//输出:
true
false
getter、setter方法没有用,可以不写。我的另外一篇里面也有对equals重写的,可以一起参考。Java 2.0 里面的第八章的 8.1.3 有专门一个对Object的equals重写。