Enforce “equals” in an interface

前端 未结 6 1202
醉酒成梦
醉酒成梦 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:33

    Edit: Probably not a good idea (see comment from FarmBoy). Leaving here for posterity.

    Instead of using equals(Object obj) from the Object class, make them compare it to an implementation of your interface.

    public interface MyInterface {
      public boolean equals(MyInterface mi);
    }
    

    Therefore,

    public class MyImplementation implements MyInterface {
      public boolean equals(MyInterface mi)
      {
        if(this == mi)
          return true;
        // for example, let's say that each implementation
        // is like a snowflake...(or something)
        return false;
      }
    }
    

    And then:

    public class Main {
    
      public static void main(String[] args)
      {
        Object o = new MyImplementation();
        MyImplementation mi1 = new MyImplementation();
        MyImplementation mi2 = new MyImplementation();
    
        // uses Object.equals(Object)
        o.equals(mi1);
        // uses MyImplementation.equals(MyInterface)
        mi1.equals(mi2);
        // uses Object.equals(Object)
        mi2.equals(o);
      }
    }
    

提交回复
热议问题