Can we override the equals() method in Java?


To compare two objects the object class provides a method with name equals(), this method accepts an object and compares it with the current object. If the references of these two objects are equal, then it returns true else this method returns false.

Example

In the following example we have a class Employee with two variables name, age and a parameterized constructor.

From the main method we are creating two objects by passing same values and, comparing both values using the equals() method.

Since the equals() method of the Object class returns true only if the references of the two objects are equal, this program returns false.

 Live Demo

import java.util.Scanner;
class Employee {
   private String name;
   private int age;
   Employee(String name, int age){
      this.name = name;
      this.age = age;
   }
}
public class EqualsExample {
   public static void main(String[] args) {
      Employee emp1 = new Employee("Jhon", 19);
      Employee emp2 = new Employee("Jhon", 19);
      //Comparing the two objects
      boolean bool = emp1.equals(emp2);
      System.out.println(bool);
   }
}

Output

false

Overriding the equals() method

Since Object is the super class of all Classes in java, you can override the equals method and write your own implementation

Example

 Live Demo

class Employee {
   private String name;
   private int age;
   Employee(String name, int age){
      this.name = name;
      this.age = age;
   }
   public boolean equals(Object obj) {
      if (obj == this) {
         return true;
      }
      if (!(obj instanceof Employee)) {
         return false;
      }
      Employee emp = (Employee) obj;
      return name.equals(emp.name)&& Integer.compare(age, emp.age) == 0;
   }
}
public class EqualsExample {
   public static void main(String[] args) {
      Employee emp1 = new Employee("Jhon", 19);
      Employee emp2 = new Employee("Jhon", 19);
      //Comparing the two objects
      boolean bool = emp1.equals(emp2);
      System.out.println(bool);
   }
}

Output

true

Updated on: 29-Jun-2020

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements