Object的equals()方法的重写和使用
class Student{ int sNo; String name; int age; public void lean() { System.out.println(name+"在学习"); } //重写equals方法 //我们认为学号,年龄,姓名一致的是同一个学生 public boolean equals(Object obj) { //判断标志 boolean flag = false; if(obj instanceof Student) { //把父类obj转换成子类的真身 Student student = (Student)obj; if(this.sNo == student.sNo && this.name != null && student.name != null && this.name.equals(student.name) && this.age == student.age) { flag = true; } } return flag; } } public class Test{ public static void main(String[] args) { Student student = new Student(); student.sNo = 1; student.age = 18; student.name = "小王"; Student student1 = new Student(); student1.sNo = 1; student1.age = 18; student1.name = "小王"; boolean eq = student.equals(student1); System.err.println(eq); } }