Java Reference
In-Depth Information
In most situations, this will not matter. However, there are situations in which it
does matter. Some library methods assume your class's definition of equals has the fol-
lowing heading, the same as in the class Object :
public boolean equals(Object otherObject)
We need to change the type of the parameter for the equals method in the class
Employee from type Employee to type Object . A first try might produce the following:
public boolean equals(Object otherObject)
{
Employee otherEmployee = (Employee)otherObject;
return (name.equals(otherEmployee.name)
&& hireDate.equals(otherEmployee.hireDate));
}
We needed to type cast the parameter otherObject from type Object to type
Employee . If we omit the type cast and simply proceed with otherObject , the com-
piler will give an error message when it sees
otherObject.name
The class Object does not have an instance variable named name .
This first try at an improved equals method does override the definition of equals
given in the class Object and will work well in many cases. However, it still has a
shortcoming.
Our definition of equals now allows an argument that can be any kind of object
whatsoever. What happens if the method equals is used with an argument that is not
an Employee ? The answer is that a run-time error will occur when the type cast to
Employee is executed.
We need to make our definition work for any kind of object. If the object is not an
Employee , we simply return false . The calling object is an Employee , so if the argu-
ment is not an Employee , they should not be considered equal. But how can we tell
whether the parameter is or is not of type Employee ?
Every object inherits the method getClass() from the class Object . The method
getClass() is marked final in the class Object , so it cannot be overridden. For any
object o , o.getClass() returns a representation of the class used to create o . For exam-
ple, after the following is executed:
o = new Employee();
o.getClass() returns a representation Employee.
We will not describe the details of this representation except to say that two such
representations should be compared with == or != if you want to know if two repre-
sentations are the same. Thus,
Search WWH ::




Custom Search