Problem with equals() method in inheritance that violates the symmetric behavior in Java

Abhijit Jadhav
2 min readJul 27, 2022

When we Inherit the class and override the equals method then the instanceof will violate the symmetric behavior that the equals method should follow according to the contract.

Problem with equals() method in inheritance that violates the symmetric behavior in Java

Let's see first what the contract of the equals method says. The equals method should be

  • Reflexive: for any non-null reference value x.equals(x) should be True
  • Symmetric : for any non-null value x.equals(y) and y.equals(x) both should be True.
  • Transitive: for any non-null value x.equals(y), y.equals(z), z.equals(x) all should be True
  • Consistent: for multiple invocations of x.equals(y) should always return the same value.

Now let's see how instanceof violates the symmetric behavior of the equals method during inheritance.

class Dog{
private String name;

public Dog(String name) {
super();
this.name = name;
}

@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj instanceof Dog)
return true;
return false;
}
}
class Labrador extends Dog{
public Labrador(String name) {
super(name);
}
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj instanceof Labrador)
return true;
return false;
}
}
public class Main {
public static void main(String[] args) {
Labrador rover1 = new Labrador("Rover");
Dog rover2 = new Dog("Rover");
System.out.println(rover1.equals(rover2));
System.out.println(rover2.equals(rover1));
}
}

Output:

false
true

Ideally, the output of both statements should be true.

To avoid this issue we need to make the equals() and hashcode() method final.

class Dog{
private String name;

public Dog(String name) {
super();
this.name = name;
}

@Override
public final boolean equals(Object obj) {
if (this == obj)
return true;
if (obj instanceof Dog)
return true;
return false;
}
}
class Labrador extends Dog{
public Labrador(String name) {
super(name);
}
}
public class Main {
public static void main(String[] args) {
Labrador rover1 = new Labrador("Rover");
Dog rover2 = new Dog("Rover");
System.out.println(rover1.equals(rover2));
System.out.println(rover2.equals(rover1));
}
}

Output:

true
true

This is how we can resolve the violation of symmetric behavior in the equals method during inheritance.

--

--

Abhijit Jadhav

Full Stack Java Developer and AI Enthusiast loves to build scalable application with latest tech stack