判断两个对象的内容是否相等,即各个属性值是否相等
public class EqualsExercise01 {
public static void main(String[] args) {
Person person1 = new Person("jack", 23, '男');
Person person2 = new Person("jack", 23, '男');
System.out.println(person1.equals(person2));
}
}
class Person{
private String name;
private int age;
private char gander;//性别
//equals方法比较两个对象的属性值是否相等
//重写equals方法
public boolean equals(Object obj){
//如果比较的两个对象为同一个对象,则直接返回true
if(this == obj){//xxx.equals(yyy),this表示xxx对象,obj表示传入的参数即yyy对象
return true;
}
//判断传进来的obj是否为Person类
if(obj instanceof Person){//类型是Person才进行比较
//进行向下转型,因为需要得到obj的各个属性
Person p = (Person)obj;
return this.name.equals(p.name) && this.age == p.age && this.gander == p.gander;
}
//若不是Person类型则直接返回false
return false;
}
public Person(String name, int age, char gander) {
this.name = name;
this.age = age;
this.gander = gander;
}
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 char getGander() {
return gander;
}
public void setGander(char gander) {
this.gander = gander;
}
}