2018-03-21

Effective defaults for equals and hashCode in Java?

So is it not possible to do this:

package java.lang;

public interface RootInterface {
  default boolean equals(Object other) {
    return this == other;
  }

  default int hashCode() {
    return System.identityHashCode(this);
  }
}

Then interpret all interfaces that don't extend anything as implicitly extending RootInterface? Then remove equals and hashCode from java.lang.Object, and get it to implement RootInterface?

package java.lang.Object;

public class Object implements RootInterface {
  ... // no hashCode or equals
}

Result: Interfaces can provide effective defaults for equals and hashCode? Nothing else breaks (except that RootInterface might be better off in a package not implicitly imported)?

This round tuit was brought to you by avoiding real work.


Update: It's possibly a bad idea for interfaces not to implicitly extend Object, as <?> and <? extends Object> then wouldn't be able to match any interface type, even though you could be sure the underlying object was certainly an Object.