- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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.
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
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