Note that there are some explanatory texts on larger screens.

plurals
  1. POIn Java, is it possible to require implementations of an interface to override Object methods?
    text
    copied!<p>Is it possible to require implementations of an interface to override <code>Object</code> methods?</p> <p>For example, if I have an interface that will commonly be used as keys in <code>HashMap</code>s, I may want to require all implementations of that interface to override the <code>hashCode()</code> and <code>equals()</code> methods.</p> <p>However, if I have the following interface...:</p> <pre><code>public interface MyInterface(){ @Override public int hashCode(); @Override public boolean equals(Object o); } </code></pre> <p>...the following implementation compiles:</p> <pre><code>public class MyImplementation(){ } </code></pre> <p>It does not require a method to override <code>hashCode()</code> or <code>equals()</code>, as it inherits these methods from <code>Object</code>.</p> <p>One approach could be to switch to using an abstract class instead of an interface:</p> <pre><code>public abstract class MyAbstractClass(){ @Override public abstract int hashCode(); @Override public abstract boolean equals(Object o); } </code></pre> <p>Then any class that extends this abstract class is required to override <code>hashCode()</code> and <code>equals()</code>:</p> <pre><code>// doesn't compile - requires implementation of hashCode() and equals() public class MyClass extends MyAbstractClass { } // does compile public class MyClass extends MyAbstractClass { @Override public int hashCode(){ // calculate hashcode } @Override public boolean equals(Object o){ // check equality } } </code></pre> <p>My supposition is that the difference between these is that an abstract class is an <code>Object</code>, so it's below <code>Object</code> in the hierarchy, so all extensions are required to meet the contract in the abstract class. Whereas, interfaces are not <code>Object</code>s, so don't sit in the hierarchy, but any implementation of an interface must be an <code>Object</code>, at which point it inherits the <code>Object</code> methods, and thus satisfies the interface 'contract'.</p> <p>However, back to my original question... is there a way to require implementations of an interface to override <code>Object</code> methods?</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