I have a simple base class, which is later extended by many separate classes, which potentially introduce new fields, but not necessarily. I defined an equals method in the
If you do not write you code correctly it will creates a serious problem, called asymmetry (violates contract for equality) so lets see our options.
Best Practice – Same Classes Strategy. If B is a subclass of A and each class has its own equals method, implemented using the same classes strategy, then the class B should be declared final to prevent the introduction of an asymmetric definition of equals in any future subclass of B.
Question. What if we don’t wish to make B final?
Use Composition instead of Inheritance. Whenever classes B and A, where B is a subclass of A, require different equals methods, using composition instead of inheritance is a good strategy, and if making the class B final is not an option, it is the only safe way to handle equals.
How?
public class A{
public boolean equals(Object ob){
//write your code here
}
}
class B{
A a= new A();
public B(A a){
this.a= a;
}
public boolean equals(Object ob){
//...write your code here
if(!((B)ob).a).equals(a)) return false;
//...write your code here
}
}