package com.object.test; import java.util.Date; public class Employee { int id; String name; int age; double salary; String position; Date birthday; Employee() { super(); } Employee(int id,String name,int age,double salary,String positon,Date birhtday) { this.id=id; this.name=name; this.age=age; this.salary=salary; this.position=positon; this.birthday=birhtday; } public int getId() { return id; } public void setId(int id) { this.id = id; } 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 double getSalary() { return salary; } public void setSalary(double salary) { this.salary = salary; } public String getPosition() { return position; } public void setPosition(String position) { this.position = position; } @Override public boolean equals(Object otherObject) { //检测otherObject是否是空引用 if(otherObject==null) { return false; } //检查this和otherObject是否引用同一个对象那个 if(this==otherObject) { return true; } //检测otherObject是否是Employee类的对象或者是子类对象。 if(!(otherObject instanceof Employee)) { return false; } /*if(!(this.getClass()==otherObject.getClass())) { return false; }*/ Employee e =(Employee)otherObject; if(this.id==e.id&&this.name==e.name&&this.age==e.age&&this.salary==e.salary&&this.position==e.position&&this.birthday.equals(e.birthday)) { return true; }else { return false; } } @Override public int hashCode() { return (int) (1*this.id+2*this.age+3*this.salary); } } class Manager extends Employee { double bonus; Manager(int id,String name,int age,double salary,String position,Date birthday) { super(id,name,age,salary,position,birthday); } Manager(int id,String name,int age,double salary,String position,Date birthday,double bonus) { super(id,name,age,salary,position,birthday); this.bonus=bonus; } @Override public boolean equals(Object otherObject) { if(!(super.equals(otherObject))) { return false; }else { Manager m =(Manager)otherObject; return this.bonus==m.bonus; } } @Override public int hashCode() { return super.hashCode()+4*(int)bonus; } }
package com.object.test; import java.util.Date; public class TestCalss { public static void main(String[] args) { Employee em1= new Employee(1,"xiaowang",23,3000.0,"A",new Date(10000)); Employee em2= new Employee(1,"xiaowang",23,3000.0,"A",new Date(10000)); Manager m1 =new Manager(1,"xiaowang",23,3000.0,"A",new Date(10000)); Manager m2 =new Manager(1,"xiaowang",23,3000.0,"A",new Date(10000)); System.out.println(em1.equals(em2)); System.out.println(m1.equals(m2)); System.out.println(em1.equals(m1)); System.out.println(em1.hashCode()==em2.hashCode()); System.out.println(em1.hashCode()==m1.hashCode()); } }
原文:http://blog.csdn.net/yuan514168845/article/details/19775601