关闭

java的equals方法重写注意事项

334人阅读 评论(0) 收藏 举报
分类:

java的equals方法一般情况下需要重写,以保证能够比较两个实例对象是否一致。

package chap09;

import static java.lang.System.out;
import java.util.Date;

public class EqualsTest {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		out.println("successful");
		
		Employee e1 = new Employee();
		Employee e2 = new Employee();
		
		out.println(e1 == e2);
		out.println(e1.hashCode());
		out.println(e2.hashCode());
	}

}

class Employee implements Cloneable {
	
	@Override
	public boolean equals(Object obj) {
		
		/** 
		 * equals must five steps:
		 *   1:two variable are point to the same object.
		 *   2:obj is null.
		 *   3:variables is the same Class.
		 *   4:cast obj.
		 *   5:equals each field's value(== for primitive; equals for object).
		 * */
		if (this == obj) {
			return true;
		}
		
		if ((obj == null) || (this.getClass() != obj.getClass())) {
			return false;
		}
		
		Employee other = (Employee)obj;
		
		return ((this.name.equals(other.name) &&
				(this.salary == other.salary) &&
				(this.hireDay.equals(other.hireDay))));
	}
	
	@Override
	public Employee clone() throws CloneNotSupportedException {
		
		return (Employee)super.clone();
	}
	
	private String name;
	private double salary;
	private Date hireDay;
}

class Manager extends Employee {

	@Override
	public boolean equals(Object obj) {
		
		/**
		 * derived class's equals method have three steps to equals two objects.
		 *   1:call the super object to equals with obj.
		 *   2:cast obj.
		 *   3:each field value, which are added in this class.
		 * */
		if ( !super.equals(obj)) {
			return false;
		}
		
		Manager other = (Manager)obj;
		
		return (this.bonus == other.bonus);
	}
	
	private double bonus;
}


0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:11161次
    • 积分:227
    • 等级:
    • 排名:千里之外
    • 原创:7篇
    • 转载:11篇
    • 译文:0篇
    • 评论:0条
    文章分类