Total members 11889 |It is currently Thu Mar 28, 2024 12:30 pm Login / Join Codemiles

Java

C/C++

PHP

C#

HTML

CSS

ASP

Javascript

JQuery

AJAX

XSD

Python

Matlab

R Scripts

Weka





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;
}
}
}





Author:
Proficient
User avatar Posts: 280
Have thanks: 1 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.

_________________
Please recommend my post if you found it helpful


Author:
Proficient
User avatar Posts: 228
Have thanks: 0 time
Post new topic Reply to topic  [ 2 posts ] 

  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     -  
 toString method in class php     -  
 define a Class with a Method     -  



Topic Tags

Java OOP
cron





Powered by phpBB © 2000, 2002, 2005, 2007 phpBB Group
All copyrights reserved to codemiles.com 2007-2011
mileX v1.0 designed by codemiles team
Codemiles.com is a participant in the Amazon Services LLC Associates Program, an affiliate advertising program designed to provide a means for sites to earn advertising fees by advertising and linking to Amazon.com