Inheritance - using super.equals() in subclasses that override methods used in equals of superclass
equals, inheritance, java
Solution
Compare instance variables directly rather than comparing an instance variable to its related getter method.
For example, change
&& price == item.getPrice())
to
&& this.price == item.price)
The getter method is unnecessary since private instance variables are only inaccessible outside the class structure.
Note:
I previously recommended the following:
&& this.getPrice() == item.getPrice())
While it will work in the question's example, it is not well suited for all cases. Consider if the subclass `DiscountedItem` declared the method `getPrice` as such:
@Override
public float getPrice() {
return Math.floor(super.getPrice());
}
This would result in the false equivalence:
DiscountedItem firstItem = DiscountedItem(1, "", 1.1, "");
DiscountedItem secondItem = DiscountedItem(1, "", 1.0, "");
firstItem.equals(secondItem); // Returns true despite different prices.
Problem
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?