aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Overriding 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 "Overriding equals()" Watch "Overriding equals()" New topic
Author

Overriding equals()

Ganesha Kumar
Ranch Hand

Joined: May 04, 2006
Posts: 56
In the book, K&B the equals method is overridden as

if ((o instanceof Moof) && (((Moof)o).getMoofValue()
== this.moofValue)) {
return true;
} else {
return false;
}

This code gives NullPointerException if 'o' is null. Should the equals() method return 'true' if two objects are null.
Anupam Sinha
Ranch Hand

Joined: Apr 13, 2003
Posts: 1088
Should the equals() method return 'true' if two objects are null.


No that would give you a null pointer exception because you are trying to invoke a method on null. Like null.equals().

Secondly I don't think in your code o is null. I guess the reference variable that you are calling equals() on is null. Had o been null it would not had thrown a null pointer exception but would had returned false.
As this would
Chandra Bhatt
Ranch Hand

Joined: Feb 28, 2007
Posts: 1707
Hi,

[Ganesha:]

... code gives NullPointerException if 'o' is null. Should the equals() method return 'true' if two objects are null.


One rule of equals() says, under all circumstances
a.equals(null) ==false

Where ofcource "a" can't be null, otherwise NullPointerException.

And it is the matter of thinking for a while, how can you even call the equals method to compare two nulls. You can't call a method using a
reference variable that is null. So no chance to even reach the inside the equals method code.

null is fortunate enough to be passed anywhere where reference is required and it never means that it can dare to break the rules.


Thanks,


cmbhatt
Jesse Custer
Ranch Hand

Joined: Feb 07, 2007
Posts: 45
Hi Ganesha, If I have understood correct this is what you are trying to do:



You will get a NullpointerException when you run this code, but not because of line 2. The Exception is thrown at line 1 because you are trying to call the equals() method on a null object.


Ganesha Kumar
Ranch Hand

Joined: May 04, 2006
Posts: 56
Thanks for clearing my doubt
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Overriding equals()