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 Final Class && Abstract Class?

0 Answers   HCL,


Thanks A.jyotsna, Can u tell me differnce between abstract class and interface vikash

4 Answers  


What does next mean in java?

0 Answers  


what is difference between length and length()?

8 Answers  


What does flagged out mean?

0 Answers  






How to define a constant variable in Java?

1 Answers   TCS,


Considering notepad/ie or any other thing as process, what will happen if you start notepad or ie 3 times? Where 3 processes are started or 3 threads are started?

0 Answers  


Tell me about your ability to work under pressure

0 Answers   AXA,


What is an enumeration?

0 Answers  


What is oop principle in java?

0 Answers  


What are the advantages of unicode?

0 Answers  


what is abstract method with example?

6 Answers   Infosys, Virtusa,


Categories