I've been testing a code and stumbled across a problem: Should you call super.equals()
method in subclass that can override some of the methods used in equals()
method of the super class?
Let's consider the following code:
public abstract class Item {
private int id;
private float price;
public Item(int id, String name, float price, String category) {
this.id = id;
this.name = name;
this.price = price;
this.category = category;
}
public int getID() {
return id;
}
public float getPrice() {
return price;
}
@Override
public boolean equals(Object object){
if(object instanceof Item){
Item item = (Item) object;
if( id == item.getID()
&& price == item.getPrice())
{ return true; }
}
return false;
}
}
And the subclass DiscountedItem:
public class DiscountedItem extends Item {
// discount stored in %
private int discount;
@Override
public boolean equals(Object object) {
if(object instanceof DiscountedItem){
DiscountedItem item = (DiscountedItem) object;
return (super.equals(item)
&& discount == item.getDiscount()
);
}
return false;
}
public int getDiscount() {
return discount;
}
@Override
public float getPrice() {
return super.getPrice()*(100 - discount);
}
}
I've been just re-reading Angelika Langer's secrets of equals(), where she even states:
There is agreement that super.equals() should be invoked if the class has a superclass other than Object.
But I think it's highly unpredictable when the subclass will override some of the methods. For instance when I compare 2 DiscountedItem
objects using equals, the super method is called and item.getPrice()
is dynamically dispatched to the correct method in the subclass DiscountedItem
, whereas the other price value is accessed directly using variable.
So, is it really up to me (as I should implement the method correctly) or is there a way around it?