美文网首页
Java核心技术(卷I) 10、Object类

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

作者: kaiker | 来源:发表于2021-02-28 17:04 被阅读0次

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

1、Object类型的变量

  • 可以使用Object类型的变量引用任何类型的对象
    Object obj = new Employee("Harry Hacker", 35000)
  • 如果要对其中内容进行具体操作,还需要清楚对象原始类型
  • 只有基本类型(int float等)不是对象

2、equals方法

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

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

  • 一个重写equals的例子
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);
   }
  • 在子类中定义equals时,首先调用超类equals,因为子类是对超类的扩展
  • 编写equals方法的六点建议:
  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方法

  • 散列码是由对象导出一个整型值
  • 每个对象都有一个默认的散列码
  • 如果equals是true,hashcode应当是一样的,但hashcode一样,可能是两个不同对象

4、toString

  • 常见格式是:类的名字,方括号括起来的字段值
public String toString()
   {
      return getClass().getName() + "[name=" + name + ",salary=" + salary + ",hireDay=" + hireDay
            + "]";
   }

相关文章

网友评论

      本文标题:Java核心技术(卷I) 10、Object类

      本文链接:https://www.haomeiwen.com/subject/jcrnxltx.html