Home » Core Java » equals() method and its contract

equals() method and its contract

What is equals() method and explain its contract ?

equals() method is defined in the top level class of Java i.e. Object class .

Syntax :

The above syntax is the default implementation of equals() method in Object class and this is the reference of the Object class.

Contract of equals() method :
1. It is reflexive .
For any reference value x ,x.equals(x) always be true.
2. It is refeixive.
For any two reference values x and y .Both x.equals(y) and y.equals(x) will always return same result.
3. It is transitive.
For any three reference values x,y and z.If x.equals(y) return true and y.equals(z) returns true ,then x.equals(z) will always return true.
4. For any not null reference value of x , x.equals(null) will always return false.
5. It is consistent.x.equals(x) will always return true ,it does no matter how many times you invoke this.

How to override equals() method ?
In the below program I have shown how to override equals() method.

Steps to override equals() method:
1. Do null check.If object is null ,then return false.
2. Do getClass() check .If object is not of same Class type ,then return false.
3. Do instanceof check.If object is not instance of the class,then return false.
4. If object is instance of the class ,then check if both objects are equal or not.Compare all the fields are get true or false ,based on equality.

To generate equals() and hashCode(),right click on the class,then on source and then click on Generate hashCode() and equals()


1 Comment

Leave a comment

Your email address will not be published. Required fields are marked *

9 + 3 =