2

Many people don't like to use instanceof, but I find that in many cases we have few other options when it comes to the equals method. Take a look at the class below:

class A {   
    int n;
    public A(int n) { this.n = n; }

    @Override
    public boolean equals(Object o) {
        return false;
    }

    public boolean equals(A o) {
        return n == o.n;
    }   
}

I've never seen something like this done, but could it serve as a replacement for having to use instanceof to test if an Object is an A? Or are there other problems that I'm not thinking of?

arshajii
  • 127,459
  • 24
  • 238
  • 287
  • 1
    I'm curious, why not use `instanceof`? Even the examples that use something like [EqualsBuilder](http://stackoverflow.com/questions/5038204/apache-commons-equals-hashcode-builder) have `instanceof`. –  Nov 21 '12 at 16:07
  • Didn't get the reason to not using it. I always use it in games. – Sri Harsha Chilakapati Nov 21 '12 at 16:10
  • 1
    @Peter is correct, the overloaded method is not dynamically bound, so this method will rarely get called in typical usage. http://stackoverflow.com/questions/321864/java-dynamic-binding-and-method-overriding/322234#322234 – Robin Nov 21 '12 at 16:11
  • I have nothing against `instanceof`, I was just curious about this question. – arshajii Nov 21 '12 at 16:22

3 Answers3

8

could it serve as a replacement for having to use instanceof to test if an Object is an A?

No. This is because the method called is chosen staticly i.e. only equals(object o) will be called in most situations.

You can write

@Override
public boolean equals(Object o) {
    return o instanceof A && n == ((A) o).n;
}
Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
0

The collections, Swing components and other classes that use equals will still call the equals(Object o) version and that will return false always.

The example will work when explicitly calling the equals(A o) method only.

Dan D.
  • 32,246
  • 5
  • 63
  • 79
0

This block of code is overloading not overriding equals. Also don't forget to check for o == null. Alternates to instanceof include getClass().equals(other.getClass()) and using A.isAssignableFrom(other.getClass())

Allen Parslow
  • 209
  • 1
  • 6