How to override a equals() method and what is the use?



How to override a equals() method and what is the use?..

Answer / rohan

equals is a method in Object class..
By default in java all the classes extend object class so
any two object can be compared using the equals method...

Provided user implement their own equals method(Override),
because the original equals method compares two objects by
their reference..

If you have a class

class A
{
int value;
p s v m(String args[]){
A obj1= new A();
abj1.value = 10;
A obj2= new A();
abj2.value = 10;

// now if try to compare these two classes

sop(obj1.equals(obj2)) // Result will be always false
} //unless you override
the equals method

boolean equals(A a){
if (a.value == this.value)
return true;
else
return false;
}//Placing this method in the above class will override
the equals method and you will be able to compare
actually the properties of those two object not
their references.

Is This Answer Correct ?    7 Yes 0 No

Post New Answer

More Core Java Interview Questions

What is the difference between actual and formal parameters?

0 Answers  


What is exception and error? and what is the difference between them?

2 Answers  


What is a default constraint?

0 Answers   HCL,


What does 0 mean in boolean?

0 Answers  


Is c better than java?

0 Answers  






difference between arraylist and linkedlist otherthan performance

2 Answers   L&T,


Can an interface implement another interface?

0 Answers  


What is the default initialized value of a boolean type variable?

3 Answers  


What's the difference between int and integer in java?

0 Answers  


Hi Friends, can u give me Real Time example for interface and abstract class.(With Banking Example)

4 Answers  


What is a ternary operator in java? What is an interface?

0 Answers  


Why is singleton class used?

0 Answers  


Categories