How do I override the equals method in the object class?
i.e I have
class Person{
//need to override here
public boolean equals (Object obj){
}
The only reason to use getClass()
rather than instanceof
is if one wanted to assert that both references being compared point to objects of the exact same class rather than objects implementing the same base class.
Say we have an Employee
e and a Manager
m (extends Employee
).
m instanceof Employee
would yield true, m.getClass() == Employee.class
would return false.
In some cases the latter might be preferred, but rarely in case of comparison of instances in equals()
or hashCode()
methods.