Object是所有类的始祖,java中的每个类的都是它拓展而来的。
Object的euqals方法、hashCode方法、getClass方法和toString方法在操作对象时是非常有用的方法。
1.euqals方法
/** *员工类 */ import java.util.Date; import java.util.GregorianCalendar; import java.util.Objects; public class Employee { /** *@param name 员工姓名 *@param salary 员工工资 *@param hireDate 雇用日期 */ private String name; private double salary; private Date hireDay; /** *构造方法 初始化员工类的字段 */ public Employee(String n,double s,int year,int month,int day) { name=n; salary=s; GregorianCalendar calendar=new GregorianCalendar(year,month-1,day); hireDay=calendar.getTime(); } /** *私有字段访问器 */ public String getDate() { return name; } public double getSalary() { return salary; } public Date getHireDay() { return hireDay; } /** *涨工资的方法 */ public void raiseSalary(double byPercent) { double raise=salary*byPercent/100; salary+=raise; } /** *重写euqals方法、hashCode方法和toString方法 */ @Override public boolean equals(Object obj) { if(this==obj) return true; if(obj==null) return false; if(getClass()!=obj.getClass()) return false; Employee other=(Employee)obj; return Objects.equals(name,other.name)&&salary==other.salary&&Objects.equals(hireDay,other.hireDay); } @Override public int hashCode() { return Objects.hash(name,salary,hireDay); } @Override public String toString() { return "\t"+getClass().getName()+"\t员工姓名:\t"+name+"\t员工工资:\t"+salary+"\t雇用日期:\t"+hireDay; } }
/** *经理类 增加了奖金字段 */ public class Manager extends Employee { private double bonus; public Manager(String n,double s,int year,int month,int day) { super(n,s,year,month,day); bonus=0; } //设置奖金的方法 public void setBonus(double b) { bonus=b; } /** *重写Employee的getSalary、equals和方法 **/ @Override public double getSalary() { double base=super.getSalary(); return base+bonus; } @Override public boolean equals(Object obj) { if(!super.equals(obj)) return false; Manager other=(Manager)obj; return other.bonus==bonus; } @Override public String toString() { return super.toString()+"\t经理奖金:\t"+bonus; } }
//测试类 /** *@author lijtaos@sina.com *@version 1.0 2015-04-17 **/ public class Test { public static void main(String[] args) { Employee tom=new Employee("Tom",7500,2010,3,15); Employee tom1=tom; Employee tom2=new Employee("Tom",7500,2010,3,15); tom1.raiseSalary(15); Manager bob=new Manager("Bob",10000,2010,3,15); bob.raiseSalary(10); bob.setBonus(25000); System.out.println("tom==tom1:\t"+(tom.equals(tom1))); System.out.println("tom==tom2:\t"+(tom.equals(tom2))); System.out.println("bob=======\t"+bob); System.out.println("tom=======\t"+tom); System.out.println("tom1======\t"+tom1); System.out.println("tom2======\t"+tom2); } }
原文地址:http://blog.csdn.net/sinat_26342009/article/details/45100967