Granny's Programming Pearls
"inside of every large program is a small program struggling to get out"
JavaRanch.com/granny.jsp
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Overriding equals()

 
Ganesha Kumar
Ranch Hand
Posts: 56
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 1090
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 1710
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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,
 
Jesse Custer
Ranch Hand
Posts: 45
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 56
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks for clearing my doubt
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic