Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>A clarification about the <code>obj.getClass() != getClass()</code>.</p> <p>This statement is the result of <code>equals()</code> being inheritance unfriendly. The JLS (Java language specification) specifies that if <code>A.equals(B) == true</code> then <code>B.equals(A)</code> must also return <code>true</code>. If you omit that statement inheriting classes that override <code>equals()</code> (and change its behavior) will break this specification.</p> <p>Consider the following example of what happens when the statement is omitted:</p> <pre><code> class A { int field1; A(int field1) { this.field1 = field1; } public boolean equals(Object other) { return (other != null &amp;&amp; other instanceof A &amp;&amp; ((A) other).field1 == field1); } } class B extends A { int field2; B(int field1, int field2) { super(field1); this.field2 = field2; } public boolean equals(Object other) { return (other != null &amp;&amp; other instanceof B &amp;&amp; ((B)other).field2 == field2 &amp;&amp; super.equals(other)); } } </code></pre> <p>Doing <code>new A(1).equals(new A(1))</code> Also, <code>new B(1,1).equals(new B(1,1))</code> result give out true, as it should.</p> <p>This looks all very good, but look what happens if we try to use both classes:</p> <pre><code>A a = new A(1); B b = new B(1,1); a.equals(b) == true; b.equals(a) == false; </code></pre> <p>Obviously, this is wrong.</p> <p>If you want to ensure the symmetric condition. a=b if b=a and the Liskov substitution principle call <code>super.equals(other)</code> not only in the case of <code>B</code> instance, but check after for <code>A</code> instance:</p> <pre><code>if (other instanceof B ) return (other != null &amp;&amp; ((B)other).field2 == field2 &amp;&amp; super.equals(other)); if (other instanceof A) return super.equals(other); else return false; </code></pre> <p>Which will output:</p> <pre><code>a.equals(b) == true; b.equals(a) == true; </code></pre> <p>Where, if <code>a</code> is not a reference of <code>B</code>, then it might be a be a reference of class <code>A</code> (because you extend it), in this case you call <code>super.equals()</code> <strong>too</strong>.</p>
 

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