N
N
natomist2014-06-19 10:52:14
Java
natomist, 2014-06-19 10:52:14

How to correctly implement the equals and hashCode methods for classes that inherit from each other in Java?

Suppose someone has developed class A and implemented the following equals method for it:

public boolean equals(Object arg) {
    if (this == arg)
      return true;
    if(!(arg instanceof A))
      return false;
    return [сравниваем поля класса A]
  }

Someone else created a class B that inherits from A and implemented a similar equals method for it.
And now we may have a situation where a.equals(b) == true, because the subset of class A fields is the same for both objects, and the hashCode of both objects will be different.
In the opposite comparison, b.equals(a) will always be false, because these are objects of different types. Those. we break the symmetry of the equals method.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
E
eyeless_watcher, 2014-06-19
@natomist

Instead , you
should explicitly compare classes
. Plus, there is not enough check that arg is not null.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question