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

Problem with equals() method in inheritance that violates the symmetric behavior in Java
  • 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.
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));
}
}
false
true
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));
}
}
true
true

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Abhijit Jadhav

Abhijit Jadhav

296 Followers

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