Reputation: 121
OK so so let's say you have two classes: ClassA
and ClassB
ClassA
extends Object
and ClassB
extends ClassA
ClassA
has no argument constructorClassB
has an integer variable x and a constructor with an integer argument that initializes xClassA
doesn't override equals
that it's inhering from Object
ClassB
overrides equals
so that two objects of ClassB
are considered equal if the integer x has the same value in both objects.
//In Class B you have this method:
public boolean equals (Object obj) {
if (obj == null) {
return false;
}
if (obj.getClass() != this.getClass()) {
return false;
}
if (!super.equals(obj)) {
return false;
}
B b = (B) obj;
return this.x == b.x;
}
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
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
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