Object类:所有类的超类,如果没有明确指出超类,Object就被认为是这个类的超类
1、Object类型的变量
可以使用Object类型的变量引用任何类型的对象
Object obj = new Employee("Harry Hacker", 35000)
如果要对其中内容进行具体操作,还需要清楚对象原始类型
只有基本类型(int float等)不是对象
2、equals方法
Object类中实现的equals方法将确定两个对象引用是否相等
一个重写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方法的六点建议:
显示参数命名为otherObject,稍后将它强制转换成另一个名为other的变量
检测this和otherObject是否相等 if (this == otherObject) return true
检测otherObject是否为null
比较this和otherObject类 if(getClass() != otherObject.getClass()) return false 如果所有子类具有相同语义可以用if(!(otherObject instanceof ClassName)) return false
将otherObject强制转换为相应类型变量 ClassName other = (ClassName) otherObject
根据相等性概念的要求比较字段(自定义比较逻辑)
3、hashCode方法
散列码是由对象导出一个整型值
每个对象都有一个默认的散列码
如果equals是true,hashcode应当是一样的,但hashcode一样,可能是两个不同对象
4、toString
常见格式是:类的名字,方括号括起来的字段值
public String toString()
{
return getClass().getName() + "[name=" + name + ",salary=" + salary + ",hireDay=" + hireDay
+ "]";
}