

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- 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
- Related Questions & Answers
- Can we override the static method in Java?
- Can we override the main method in java?
- Can we override a start() method in Java?
- Can we override a protected method in Java?
- Can we overload or override a static method in Java?
- Can we override a private or static method in Java
- Can we override only one method while implementing Java interface?
- Can we override private methods in Java
- Can we override final methods in Java?
- Can we override default methods in Java?
- Can we to override a catch block in java?
- Can we Overload or Override static methods in Java?
- Why can’t we override static methods in Java?
- Java String equals() method.
- Override the toString() method in a Java Class