Is it possible to require implementations of an interface to override Object methods?
For example, if I have an interface that will commonly be used as keys in HashMaps, I may want to require all implementations of that interface to override the hashCode() and equals() methods.
However, if I have the following interface…:
public interface MyInterface(){
@Override
public int hashCode();
@Override
public boolean equals(Object o);
}
…the following implementation compiles:
public class MyImplementation(){
}
It does not require a method to override hashCode() or equals(), as it inherits these methods from Object.
One approach could be to switch to using an abstract class instead of an interface:
public abstract class MyAbstractClass(){
@Override
public abstract int hashCode();
@Override
public abstract boolean equals(Object o);
}
Then any class that extends this abstract class is required to override hashCode() and equals():
// 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
}
}
My supposition is that the difference between these is that an abstract class is an Object, so it’s below Object in the hierarchy, so all extensions are required to meet the contract in the abstract class. Whereas, interfaces are not Objects, so don’t sit in the hierarchy, but any implementation of an interface must be an Object, at which point it inherits the Object methods, and thus satisfies the interface ‘contract’.
However, back to my original question… is there a way to require implementations of an interface to override Object methods?
There is no way to accomplish what you want using only interfaces.
An alternative (and possibly clearer) way to do this by forcing the use of an abstract base class is as follows: