属性
private int id;
private String name;
private String sex;
private int age;
构造方法
public Student(int id, String name, String sex, int age) {
super();
this.id = id;
this.name = name;
this.sex = sex;
this.age = age;
}
封装
public boolean equals(Object obj) {
if (this == obj)
return true;
if(obj instanceof Student) {
Student other = (Student) obj;
if (age != other.age)
return false;
if (id != other.id)
return false;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name)) {
return false;
}
if (sex == null) {
if (other.sex != null)
return false;
} else if (!sex.equals(other.sex)) {
return false;
}
return true;
}else {
return false;
}
}
入口
Student s = new Student(1001, "张三","男",20);
Student s1 = new Student(1001, "张三","男",20);
System.out.println(s.equals(s1));
思路
equals未重写时时判断字符串是否一样,用等于判断基本数据类型时是比较值是否相等,比较字符串时是比较地址是否相等,我们重写equals时让其比较对象的值是否相等,首先判断输入的对象是否属于要比较的类,如果不是就不相等,反之将其转化成要比较的类,然后一一比较里面属性是否都相等,基本数据类型用int比较,String类型就用equals比较,当所有都一样时说明时一样的,如果有一项不一样就不是一样的.