Can we override the equals() method in Java?

Java 8Object Oriented ProgrammingProgramming

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
raja
Published on 05-Jul-2019 08:36:00
Advertisements