Java override Object equals() method

后端 未结 9 714
被撕碎了的回忆
被撕碎了的回忆 2020-12-19 07:21

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){

}
         


        
9条回答
  •  一整个雨季
    2020-12-19 08:25

    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.

提交回复
热议问题