jQuery in Action, 3rd edition
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Want hepl to understand Implementin an equals() Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Want hepl to understand Implementin an equals()" Watch "Want hepl to understand Implementin an equals()" New topic

Want hepl to understand Implementin an equals()

Deepak Bobal
Ranch Hand

Joined: Feb 06, 2008
Posts: 96
In K @ B book of java5 on page 526 an example of Implementin an equals() method is given.I am getting problem to understand last few lines.

if ((o instanceof Moof) && (((Moof)o).getMoofValue()
== this.moofValue))
i am unable to understand the condition given after '&&'.
this.moofValue means moofvalue ,the current object holds.But what about (((Moof)o).getMoofValue()???
How they are different?/

Complete program is like this------

public class EqualsTest {
public static void main (String [] args) {
Moof one = new Moof(8);
Moof two = new Moof(8);
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) {
if ((o instanceof Moof) && (((Moof)o).getMoofValue()
== this.moofValue)) {
return true;
} else {
return false;


Constant dripping hollows out a stone....
Jesper de Jong
Java Cowboy
Saloon Keeper

Joined: Aug 16, 2005
Posts: 15081

In the equals() method, you are comparing the contents of the current object (on which the method is called) with the contents of some other object, that is passed to the method as an argument 'o'.

Looking at this expression:


You have 'o', which is an Object. To get the moofValue of that object, it first has to be cast to a Moof object, by doing (Moof)o. Then the method getMoofValue() is called on the casted object to retrieve the value. You can write this in multiple steps like this, I hope this makes it clear what the expression does to you:

Moof m = (Moof)o;

Looking at the complete expression:

if ((o instanceof Moof) && (((Moof)o).getMoofValue() == this.moofValue))

This is what happens:

1. Check that the object 'o' is really an instance of class Moof.
2. Get the moofValue from the object 'o'.
3. See if the moofValue from object 'o' and from the current object are equal.
[ February 15, 2008: Message edited by: Jesper Young ]

Java Beginners FAQ - JavaRanch SCJP FAQ - The Java Tutorial - Java SE 8 API documentation
I agree. Here's the link: http://aspose.com/file-tools
subject: Want hepl to understand Implementin an equals()
It's not a secret anymore!