Switch to full style
Java2 codes,problems ,discussions and solutions are here
Post a reply

Overriding Equals Method

Wed Oct 22, 2008 2:07 am

I have a doubt. When I compile and run this program, it gives the o/p
True
9
8.
Actually this program is creating 2 objects of same type with 2 different
parameters (8 and 9) and comparing the 2 objects with overridden Equals method.
Could anyone please explain me, why "this.moofValue" is getting the value "8"
when it actually passes "9". (line marked XXX)

Thanks & Regards

Chooti Baba.


Code:
public class EqualsTest
{
public static void main (String [] args)
{
Moof one = new Moof(8);
Moof two = new Moof(9);
if (one.equals(two))
{
System.out.println("one and two are equal");
}
}
}

class Moof
{
private int moofValue;
Moof(int val)
{
moofValue = val;
}
public int getMoofValue()
{
return moofValue;
}
public boolean equals(Object o)
{
System.out.println(o instanceof Moof);
System.out.println(((Moof)o).getMoofValue());
System.out.println(this.moofValue); //XXX
if ((o instanceof Moof) && (((Moof)o).getMoofValue() == this.moofValue))
{
return true;
}
else
{
return false;
}
}
}




Re: Overriding Equals Method

Wed Oct 22, 2008 2:08 am

Hi,

you are getting this.moofValue as 8 because, you are calling the
equal method on the Object one, which has a value of 8. If you
reverse the caller and the argument in equals method, say :
if( two.equals(one)) .... then you will get the result as you wanted,
i.e. value 9 on the calling object.

Post a reply
  Related Posts  to : Overriding Equals Method
 overriding method in php     -  
 Overriding the Function of a Base Class     -  
 overriding the direction of text within body content     -  
 What is an abstract method     -  
 What is a static method     -  
 Creating a Method in jsp     -  
 What is a native method     -  
 use out object in a method at jsp     -  
 problem with JcheckBox method     -  
 Calling an Overridden Method in php     -  

Topic Tags

Java OOP