Enforce “equals” in an interface

前端 未结 6 1200
醉酒成梦
醉酒成梦 2021-02-15 04:06

I have an interface and I want everyone who implements this interface to implements an overrridden \"equals\" method.

Is there a way to make sure that happens?

6条回答
  •  生来不讨喜
    2021-02-15 04:43

    No, you only can create an abstract class instead of an interface like this:

    public abstract class MyApi {
    
      public final boolean equals(Object other) {
        if (other == this) {
          return true;
        }
        if (other instanceof MyApi) {
          return equals((MyApi)other);
        }
        return false;
      }
    
      protected abstract boolean equals(MyApi other);
    
    }
    

    or a more simple version:

    public abstract class MyApi {
    
      public boolean equals(Object other) {
        throw new UnsupportedOperationException("equals() not overridden: " + getClass());
      }
    
    }
    

    EDIT (gave it a try after the comment from @CodeConfident, thanks! Never assumed it would work):

    You can also simply declare equals() in an abstract class (not in an interface!) and therefore hide the Object implementation and enforce a new implementation in any subclass:

    public abstract class MyApi {
    
      public abstract boolean equals(Object obj);
    
      public abstract int hashCode();
    
    }
    

    Anyway you should always implement equals() and hashCode() together to fulfil the contract.

提交回复
热议问题