建一个学生类
public class Student {
private String name;
private int age;
//构造方法
public Student() {
super();
}
public Student(String name, int age) {
super();
this.name = name;
this.age = age;
}
@Override
public boolean equals(Object obj) {
// 首先name是String类型,String类也继承Object类,所以也继承equals方法,
//将此字符串与指定的对象比较。当且仅当该参数不为 null,并且是与此对象表示相同字符序列的 String 对象时,结果才为 true。
//如果自己比自己直接true
if(this==obj){
return true;
}
//如果类名不同
if(!(this instanceof Student)){
return false;
}
//但是Object没有name和age属性,所以要进行类型向下装换
Student s=(Student)obj;
return this.name.equals(s.name)&&this.age==s.age;//比较是boolean直接retrun
}
}
测试类
/*
* 类 Object
* equals
*
*equals(Object obj)指示其他某个对象是否与此对象“相等”。 比较的是两个对象的地址,每次实例化对象地址都不同,比较就没有意义所以要进行重写
*/
public class EqualsDemo {
public static void main(String[] args) {
Student st1=new Student("小明", 20);
Student st2=new Student("小红", 20);
Student st3=new Student("小明", 20);
System.out.println(st1.equals(st2));
System.out.println(st1.equals(st3));
}
}
输出结果
false
true