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

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

+ "]";

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值