filpa
filpa

Reputation: 3654

Would overriding equals() with multiple instanceof tests be feasible for different objects?

Say I have a class where I would have to check for multiple different types of objects. Would it be feasible/possible to override equals() in the following manner?

public boolean equals(Object o){
    if(o == null) return false;
    if(o instanceof class1){
        return this.class1.equals((class1) o);
    if(o instanceof class2){
        return this.class2.equals((class2) o);
    ...

}

Would this ever be useful? I assume here that I create a static overloaded equals() method in the respective classes (though maybe polymorphism would take care of that automatically as long as I cast?).

Upvotes: 1

Views: 272

Answers (4)

user207421
user207421

Reputation: 310985

If you're sure that it won't lead to mutual recursion you can just return that.equals(this). However in general object equality implies either equality of classes, or at least a coherent inheritance relationship between them.

Upvotes: 0

ewan.chalmers
ewan.chalmers

Reputation: 16245

It seems like you want a method to check whether a specified object is equal to at least one of various member variables in the receiver.

It is inappropriate to override java.lang.Object#equals for this purpose.

You should instead provide a different method, e.g.

public boolean hasEquals(Object o) { // your impl }

Upvotes: 1

zeller
zeller

Reputation: 4974

Semantically I don't think this is a good idea. Equals should not be based on class types but instance variables. Apart from that, an Apple should never be equal to a Pear but only to other apples.

Upvotes: 1

ratchet freak
ratchet freak

Reputation: 48216

I very much doubt that because you can easily violate the transitivity of equals this way (x.equals(y) && x.equals(z) implies y.equals(z))

unless of course you do a very throughout setup involving all classes but that would be a pain to get right

Upvotes: 3

Related Questions