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

Answer Posted / 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       View All Answers


Please Help Members By Posting Answers For Below Questions

what is object-oriented programming in java?

584


What is meant by flickering?

651


Why is boolean important?

586


What is boolean query?

524


Why string is not a wrapper class?

640






What is anonymous inner class?

609


Is string a class?

554


Define iterator and methods in iterator?

545


What are the 3 types of control structures?

527


What is immutable in java?

537


What are data structures in java?

527


Can we sort list in java?

598


Explain heap sort?

698


Explain constructors and types of constructors in java.

641


What is use of inner class in java?

512