对super.equals方法的讨论
正在学Java,下面是一个对 Core Java中例子EqualsTest.java的一个简化版本,以突出我想讨论的问题:
public class EqualsTest
{
public static void main(String[] args)
{
Manager carl = new Manager("Carl Cracker", 80000);
Manager boss = new Manager("Carl Cracker", 80000);
System.out.println("carl.equals(boss): "
+ carl.equals(boss));
}
}
class Employee
{
public Employee(String n, double s)
{
name = n;
salary = s;
}
public boolean equals(Object otherObject)
{
if (this == otherObject) return true;
if (otherObject == null) return false;
//我想讨论的地方
if (getClass() != otherObject.getClass())
return false;
Employee other = (Employee)otherObject;
return name.equals(other.name)
&& salary == other.salary;
}
private String name;
private double salary;
private Date hireDay;
}
class Manager extends Employee
{
public Manager(String n, double s)
{
super(n, s);
bonus = 0;
}
public boolean equals(Object otherObject)
{
if (!super.equals(otherObject)) return false;
Manager other = (Manager)otherObject;
// super.equals checked that this and other belong to the
// same class
return bonus == other.bonus;
}
private double bonus;
}
讨论1:
两个子类对象做比较,调用超类的equals方法,当程序执行到这一步时,查看表达式"this.getClass().getName()"的值为"Manager",我原本还以为该"Employee"。这在文档java.lang.Object中对getClass方法给出了说明,它returns the runtime class of an object。我觉得这个实现is interesting :P ,因为在Object类中它被声明为public final Class getClass(),而声明为final的方法
是不能被子类覆盖的,所以不是通过动态绑定的机制。
讨论2:
另外,我觉得执行super.equals(otherObject),到了超类的equals方法中后,this引用就指向carl(子类对象)所指对象,这个隐式参数的传递让人觉得比较含糊。
问题:
我想在超类(Employee类)的equals方法中,比较那里的this引用和otherObject参数是否指向同一块内存区域,如何做?表达式this == otherObject是比较两个引用的地址。