直接上代码
@Override
public boolean equals(Object obj) {
if(this==obj)
return true;//两个对象是同一个,那必然相等
if(!(obj instanceof doctor)){
return false;//判断一下是都是子类,如果不是子类那必然不会相等
}
doctor d=(doctor) obj;//向下转型以便比较
return this.name.equals(d.name)&&this.age==d.age&&this.gender==d.gender&&this.job.equals(d.job)&&this.sal==d.sal;//比较这两个的所有属性是不是全部相等,这里的equals是obj里面的,没有重写过的
}
里面提到了个equals()和==我们来看一下题目有上面区别
基本数据类型就是指的是int,double这些
最后奉上一个完整的样例代码方便测试
public class test {
public static void main(String []args) {
doctor d1 = new doctor("jack", 20, "it", 1, 2000);
doctor d2 = new doctor("jack", 20, "it", 1, 2000);
System.out.println(d1.equals(d2));
}
}
class point{
private int x,y;
public point(int x, int y) {
this.x = x;
this.y = y;
}
public int getX() {
return x;
}
public int getY() {
return y;
}
public void setX(int x) {
this.x = x;
}
public void setY(int y) {
this.y = y;
}
}
class doctor{
private String name;
private int age;
private String job;
private int gender;
private double sal;
public doctor(String name, int age, String job, int gender, double sal) {
this.name = name;
this.age = age;
this.job = job;
this.gender = gender;
this.sal = sal;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
public String getJob() {
return job;
}
public int getGender() {
return gender;
}
public double getSal() {
return sal;
}
public void setName(String name) {
this.name = name;
}
public void setAge(int age) {
this.age = age;
}
public void setJob(String job) {
this.job = job;
}
public void setGender(int gender) {
this.gender = gender;
}
public void setSal(double sal) {
this.sal = sal;
}
@Override
public boolean equals(Object obj) {
if(this==obj)
return true;
if(!(obj instanceof doctor)){
return false;
}
doctor d=(doctor) obj;
return this.name.equals(d.name)&&this.age==d.age&&this.gender==d.gender&&this.job.equals(d.job)&&this.sal==d.sal;
}
}