wood burning stoves*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Implementing equals() Method 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 "Implementing equals() Method" Watch "Implementing equals() Method" New topic
Author

Implementing equals() Method

sumedha rao
Ranch Hand

Joined: Nov 26, 2010
Posts: 115

hi all,

I have started with chpt 7 and came accross this code in k and b,pg546...where i dint understand the last part of it....public boolean equals(Object o){........}



please explain i really dint understand(how can o be an instance of Moof??? )


scjp1.6,scwcd1.5!!!
Swastik Dey
Rancher

Joined: Jan 08, 2009
Posts: 1473
    
    6

Object class is the parent of all, I hope this gives you the answer. To add more if this rule was not there, probably it won't have allowed to to call the equals method of with reference of Moof, because the method expects Object reference type. Correct me if I am wrong.


Swastik
Seetharaman Venkatasamy
Ranch Hand

Joined: Jan 28, 2008
Posts: 5575

Moof extends Object implicitly! so Moof is an Object. object is a super class of all the classes
Matthew Raw
Ranch Hand

Joined: Nov 30, 2010
Posts: 76

With the help of runtime polymorphism, the Object o which is an argument to the equals method, can be ANY object - for example, one can call

etc. This would result in the condition o instanceof Moof = false and thus the method equals() would return false. This is the prefered implementation, used in the Java API - when calling equals to compare two objects of different class hierarchies, the equals method returns false.
So the method equals() can possibly return true only if the passed object o is instanceof Moof.
The instanceof test is important, because in the "if" clause, you make a down-cast and you want to avoid RuntimeException (in this case, ClassCastException).
Hope this helps.
(It may be helpful for you to review runtime polymorphism and down-casting in the K&B book.)
sumedha rao
Ranch Hand

Joined: Nov 26, 2010
Posts: 115

ok..ya right i understood about the downcasting thing...but why do we need the comparing in the 2nd expression when the if condition is satisfied with the 1st exp(downcasting) itself???

)
Swastik Dey
Rancher

Joined: Jan 08, 2009
Posts: 1473
    
    6

In the first expression, you are first checking whether the passed object is Moof or not. If it is a Moof object, then in the second expression you are checking whether both the moof objects contain the same value or not.
sumedha rao
Ranch Hand

Joined: Nov 26, 2010
Posts: 115

ok
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Implementing equals() Method