JAVA核心技术 第五章 Object 所有类的超类

来源:互联网 发布:淘宝店小二的旺旺 编辑:程序博客网 时间:2024/06/10 06:17
一 OBJECT --   在Java中,只有基本类型(primitive types)不是对象,
                          例如,数值、字符和布尔类型的值都不是对象。
                          所有的数组类型,不管是对象数组还是基本类型数组都扩展域Object类。

Java语言规范要求equals方法具有下面的特性:
                        1.自反性:对于任何非空引用x,x.equals(x)应该返回true。
                        2.对称性:对于任何引用x和y,当且仅当y.equals(x)返回true,x.equals(y)也应该返回true。
                        3.传递性:对于任何引用x、y和z,如果x.equals(y)返回true,y.equals(z)返回true,x.equals(z)也应该返回true。
                        4.一致性:如果x和y引用的对象没有发生变化,反复调用x.equals(y)应该返回同样的结果。

                        5.对于任意非空引用x.x.equals(null)应该返回false。

class Employee{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&&hireDay.equals(other.hireDay);}}//在子类中定义equals方法时,首先调用超类的equals//如果检测失败,对象就不可能相等//如果超累中的域都相等,就需要比较子类中的实例域Class Manager extends Employee{public boolean equals(Object otherObject){if(!super.equals(Object otherObject)) return false;Manager other=(Manager)otherObject;return bonus==other.bonus;}}

二 编写一个完美的equals方法的建议:
1.显示参数命名为otherObject,稍后需要将它转换成另一个叫做other的变量。
2.检测this与otherObject是否引用同一个对象。if(this==otherObject) return true;
3.检测otherObject是否为null,如果为null,返回false.这项检测是必须的. if(otherObject==null) return false;
4.比较this与otherObject是否属于同一个类.如果equals的语法在每个子类中有所变化就使用getClass检测:
if(getClass!=otherObject.getClass()) return false;
  如果所有的子类都拥有统一的语义,就使用instanceof检测:if(!(otherObject instanceof ClassName)) return false;
5将otherObject转换为响应的类类型变量:ClassName other=(ClassName) otherObject
6现在开始对所有需要比较的域进行比较.使用==比较基本数据域,使用equals比较对象域.如果所有的域都匹配,返回true;否则返回false;
return field1==other.field1&&field2.equals(other.field2)&&.....


如果子类中重新定义equals,就要在其中包含调用super.equals(other).

三 Object类的方法

1.Class getClass()

2.boolean equals(Object otherObject)

3.String toString()

4.Object clone()

5.String getName()---返回这个类的名字

6.Class getSuperclass()---以class对象的形式返回这个类的超类信息

0 0
原创粉丝点击