Java核心技术(卷I) 10、Object类

2021-02-28  本文已影响0人  kaiker

Object类:所有类的超类,如果没有明确指出超类,Object就被认为是这个类的超类

1、Object类型的变量

2、equals方法

Object类中实现的equals方法将确定两个对象引用是否相等

equals和==的区别 https://blog.csdn.net/wangzhenxing991026/article/details/109786200

public boolean equals(Object otherObject)
   {
      // a quick test to see if the objects are identical
      if (this == otherObject) return true;

      // must return false if the explicit parameter is null
      if (otherObject == null) return false;

      // if the classes don't match, they can't be equal
      if (getClass() != otherObject.getClass()) return false;

      // now we know otherObject is a non-null Employee
      Employee other = (Employee) otherObject;

      // test whether the fields have identical values
      return Objects.equals(name, other.name) && salary == other.salary && Objects.equals(hireDay, other.hireDay);
   }
  1. 显示参数命名为otherObject,稍后将它强制转换成另一个名为other的变量
  2. 检测this和otherObject是否相等 if (this == otherObject) return true
  3. 检测otherObject是否为null
  4. 比较this和otherObject类 if(getClass() != otherObject.getClass()) return false 如果所有子类具有相同语义可以用if(!(otherObject instanceof ClassName)) return false
  5. 将otherObject强制转换为相应类型变量 ClassName other = (ClassName) otherObject
  6. 根据相等性概念的要求比较字段(自定义比较逻辑)

3、hashCode方法

4、toString

public String toString()
   {
      return getClass().getName() + "[name=" + name + ",salary=" + salary + ",hireDay=" + hireDay
            + "]";
   }
上一篇下一篇

猜你喜欢

热点阅读