Java Reference
In-Depth Information
if
(object1.getClass() == object2.getClass())
System.out.println("Same class.");
else
System.out.println("Not the same class.");
will output
Same class
if
object1
and
object2
were created with the same class when
they were created using
new
, and output
Not same class
otherwise.
Our final version of the method
equals
is shown in Display 7.10. Note that we
have also taken care of one more possible case. The predefined constant
null
can be
plugged in for a parameter of type
Object
. The Java documentation says that an
equals
method should return
false
when comparing an object and the value
null
. So
that is what we have done.
On the accompanying CD, the subdirectory
improvedEquals
(of the directory for
this chapter) has a definition of the class
Employee
that includes this definition of
equals
.
extra code
on CD
Display 7.10
A Better
equals
Method for the Class
Employee
1
public boolean equals(Object otherObject)
2
{
3
if
(otherObject ==
null
)
4
return false
;
5
else if
(getClass() != otherObject.getClass())
6
return false
;
7
else
8
{
9
Employee otherEmployee = (Employee)otherObject;
10
return
(name.equals(otherEmployee.name)
11
&& hireDate.equals(otherEmployee.hireDate));
12
}
13
}