Overriding equals() method of Object class in java
Default equals() method of the java.lang.Object class compares the memory location of the objects and returns true if the two reference variables are pointing to the same memory location. i.e. they are the same objects.
Points To Remember
  • equals() method is the method of Object class.
  • It compares the memory location of the two objects.
  • equals() method in java is Reflexive. i.e, object must be equal to itself.
  • equals() method in java is Symmetric.  i.e, if a.equals(b) then b.equals(a) must be true.
  • equals() method in java is Transitive.  i.e,  if a.equals(b) and b.equals(c) the a.equals(c) must be true.
  • equals() method in java is Consistent.  i.e, if two objects are same in java then they must remain same all time until any property of any object is changed.
  • If two object are same then their hashCode() will be same, but if the two hashCodes are same then they may or may not be same.
Steps to override equals method in Java
  1. this check, if the object is same as this, then return true.
  2. null check, if the object is null return false.
  3. instanceOf() check, if both the object are an instance of same class.
Example of overriding equals()
Following example show how to override the equals() method.
public class TestClass{

    String name;   

    public TestClass(String name){
        this.name = name;

    public static void main (String args[]){
       TestClass t1 = new TestClass("Demo Object");
       TestClass t2 = new TestClass("Demo Object");

    public boolean equals(Object obj){
      if(obj == this)
          return true;
      if(obj == null)
          return false;
      if(!(obj instanceof TestClass) )
          return false;
      TestClass test = (TestClass)obj;
      return name.equals(test.name);


The above program will give the output : true.  However if we would have not overriden the equals() method, in that case the same program would have given the output as false.

No comments :

Post a Comment