3

Let's say I want to override the method equals() of Object:

    public boolean equals(Object o){
      //something
    }

    public boolean equals(SomeClass s){
      //something else
    }

SomeClass is obviously also an Object, so which method will be called if I use equals with an Instance of SomeClass as parameter?

ChopChop
  • 140
  • 8

3 Answers3

6

That's not overriding, it's overloading. If you do that you'll end up with two equals methods: one that will be invoked for (subclasees of) SomeClass instances and one for any other objects.

One thing to note is that the method binding will be static: the compiler will decide which one to call based on the declared type of your reference. Therefore, the following will invoke the equals(Object), not equals(SomeClass):

Object o = new SomeClass();
o.equals(o);  // invokes SomeClass.equals(Object)
Costi Ciudatu
  • 37,042
  • 7
  • 56
  • 92
  • Thank you for your answer. Is there a way to avoid the behavior described in the second paragraph of your post? – ChopChop Dec 15 '12 at 15:20
  • Nope, the only way is to stick to overriding the `equals(Object)` method and inside perform some `instanceof` test. – Costi Ciudatu Dec 15 '12 at 15:24
1

If you overload the function like in your example, and instantiate the object normally, the equals function with SomeClass as parameter will be called if you provide a SomeClass to the equals function. For any other class, the equals function with an Object as parameter will be called.

If you instantiate your object as a parent class, however, the behaviour is different. This has to do with dynamic binding, which is explained quite well here: Question about Java overloading & dynamic binding

Note that if you're looking to do something else if the Object is of a SomeClass type, you could also use instanceof SomeClass in your standard equals function. (Not trying to start a discussing, but it's an option)

Community
  • 1
  • 1
1

Your public boolean equals(SomeClass s) will be called when you invoke it with a parameter SomeClass or a sub class of SomeClass.

With any other object it will be public boolean equals(Object o) that's called.

But when you equals method is being called in other APIs they will call public boolean equals(Object o). Which will lead to erroneous behavior. Java Collection API is an example.

So do not overload the equals method like this.

Thihara
  • 7,031
  • 2
  • 29
  • 56