Note that there are some explanatory texts on larger screens.

plurals
  1. POInheritance - using super.equals() in subclasses that override methods used in equals of superclass
    primarykey
    data
    text
    <p>I've been testing a code and stumbled across a problem: Should you call <code>super.equals()</code> method in subclass that can override some of the methods used in <code>equals()</code> method of the super class?</p> <p>Let's consider the following code:</p> <pre><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() &amp;&amp; price == item.getPrice()) { return true; } } return false; } } </code></pre> <p>And the subclass DiscountedItem:</p> <pre><code>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) &amp;&amp; discount == item.getDiscount() ); } return false; } public int getDiscount() { return discount; } @Override public float getPrice() { return super.getPrice()*(100 - discount); } } </code></pre> <p>I've been just re-reading <a href="http://www.angelikalanger.com/Articles/JavaSolutions/SecretsOfEquals/Equals.html" rel="nofollow">Angelika Langer's secrets of equals()</a>, where she even states:</p> <blockquote> <p>There is agreement that super.equals() should be invoked if the class has a superclass other than Object.</p> </blockquote> <p>But I think it's highly unpredictable when the subclass will override some of the methods. For instance when I compare 2 <code>DiscountedItem</code> objects using equals, the super method is called and <code>item.getPrice()</code> is dynamically dispatched to the correct method in the subclass <code>DiscountedItem</code>, whereas the other price value is accessed directly using variable.</p> <p>So, is it really up to me (as I should implement the method correctly) or is there a way around it? </p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload