Object:所有类的超类

Java中每个类都是由Object类扩展而来

1、equals方法

在Object类中,这个方法用于判断两个对象是否具有相同的引用,然而对于大多数类来说,经常需要检测两个对象状态的相等性。

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;
}

为了防备name为null的情况,使用 Objects.equals方法。如果两个参数都为null,Objects.equals(a,b)返回true;如果一个参数为null,返回false;如果两个参数都不为null,调用a.equals(b)

return Objects.equals(name, other.name) && salary == other.salary;

在子类中定义equals方法时,首先调用父类的equals。只有相等时,才需要比较子类的实例域

public boolean equals(Object otherObject){
  if(!super.equals(otherObject))
    return false;
  Manager other = (Manager) otherObject;
  return bonus == other.bonus;
}

猜你喜欢

转载自www.cnblogs.com/chenzida/p/9286865.html