Angelo Rivera
Angelo Rivera

Reputation: 121

Overriding the Object class' equal method

OK so so let's say you have two classes: ClassA and ClassB

In the main if you were to run this code

    B b1 = new B(1);
    B b2 = new B(1);
    System.out.println(b1.equals(b2));

I believe "false" would be printed but I'm trying to understand why. Maybe I'm not fully understanding the concept of overriding but I just figured since B should be overriding the Object.equals method so it can make sure the x fields are the same.

What appears to be "wrong" that I'm missing?

Upvotes: 1

Views: 856

Answers (2)

Nathan Hughes
Nathan Hughes

Reputation: 96395

Your code is never going to get past the super.equals check, because (since Object.equals is comparing object references) any two different objects are always going to test false for equality. Object.equals is comparing references, the only time it returns true is if it is comparing a reference to itself.

Typically if you override equals it is because you want to compare the objects by value (like String or BigInteger), so there is no reason for referencing the super class's equals method (which compares by reference) in that case.

Upvotes: 2

koljaTM
koljaTM

Reputation: 10262

You should omit the

if (!super.equals(obj))
{
return false;
 }

because that will use the default equals() method (which checks for object identity)

Upvotes: 6

Related Questions