If we have two classes Dog(parent) and Labrador(child) as below
public class Dog {
private final String name;
public Dog(String name){
this.name = name;
}
public String getName(){
return name;
}
@Override
public final boolean equals(Object obj){
if(this==obj)
return true;
if(obj instanceof Dog){
System.out.println("In if of dog");
String objName = ((Dog)obj).getName();
return this.name.equals(objName);
}
return false;
}
}
Labrador class
public class Labrador extends Dog {
public Labrador(String name){
super(name);
}
/* @Override
public boolean equals(Object obj){
if(this==obj)
return true;
if(obj instanceof Labrador){
System.out.println("In if of labrador");
String objName = ((Labrador)obj).getName();
return this.getName().equals(objName);
}
return false;
}
}
Now there is a problem in Java at the moment. If we override the equals method in both parent and child class like we did in Dog and Labrador Class and then try to compare a Dog and Labrador object like we did here then Dog(parent object) compares to child object but its not true the other way around. The reason is Labrador Instance is an instance of Dog but Dog instance itself is not an instance of Labrador
So we make Dog and Labrador objects are try to compare them
Labrador rover = new Labrador("Rover");
Dog dog = new Dog("Rover");
System.out.println(dog.equals(rover));
System.out.println(rover.equals(dog)); //This will print false as for the reason explained below
So if in Labrador class we call equals method and pass Dog as instance then the below line of code will return false
if(obj instanceof Labrador).
So the best way to solve this problem is NOT to override the equals method in child classes Or we can mark the over-riden method in Parent class Dog as final so that is can't be overriden.