Joined: Sun Oct 19, 2008 3:47 pm Posts: 281 Has thanked: 0 time Have thanks: 1 time
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; } } }
AnswerBot
Question subject: Re: Overriding Equals Method
Posted: Wed Oct 22, 2008 2:08 am
Joined: Sun Oct 19, 2008 3:53 pm Posts: 229 Has thanked: 0 time Have thanks: 0 time
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.