当个子类中比较的内容不同时,就需覆盖父类中的equals方法来实现自己的比较方式
如:
- class Person
- {
- private String name;
- private int age;
- person(String name, int age)
- {
- this.name = name;
- this.age = age;
- }
- //通过姓名和年龄
- public boolean equals(Object obj)
- {
- if(obj instanceof Person)
- {
- Person p = (Person)obj;
- return this.name.equals(p.name)&&this.age==p.age;
- }
- return false;
- }
- }
- class Student extends Person
- {
- private String stuID;
- Student(String name, int age, String stuID)
- {
- super(name,age);
- this.stuID = stuID;
- }
- //通过姓名、年龄、学号
- public boolean equals(Object obj)
- {
- if(obj instanceof Student)
- {
- Student stu = (Student)obj;
- return this.name.equals(stu.name)&&this.age==stu.age&&this.stuID.equals(stu.stuID);
- }
- return false;
- }
- }
复制代码
假如还有个工人类继承了Person,那么就可以是姓名、年龄、工号 |