• Post Reply Bookmark Topic Watch Topic
  • New Topic

overriding equals  RSS feed

 
Ra Carter
Ranch Hand
Posts: 96
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
i have a class Person that has this code:

then somewhere else i have this:what i am finding out is that on p1.equals(null) the equals(Person) method is being called instead of equals(Object). Why is that?
 
Keith Lynn
Ranch Hand
Posts: 2409
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
When you have two methods that match a call, the most specific method will be called.
 
Ernest Friedman-Hill
author and iconoclast
Sheriff
Posts: 24217
38
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Why would you define these two separate methods using different code, anyway? Because the overload is resolved at compile time, not runtime, your equals(Person) won't be used by (for example) the Collection.contains() method, or any other method that calls equals() on Objects.

Assuming that you really, really need the optimization of an equals(Person) method (and that's a very shaky assumption) you should do



and the other method as is. Your equals(Person) needs to check for null, whereas your Object one is safe as written.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!