Enforce “equals” in an interface

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

    I guess there can be two reasons why such an equals method might be required

    1. You want to ensure that all the classes in your app (or a subset of them) "will" have the equals method. Something like standards enforcement, or making sure some of the APIs you use work as they should (and they expect equals to be implemented correctly. Say you use Maps quite a lot and want to be absolutely sure that a subset of classes are definitely possible map keys) If that is the case, this is not the way to go. In this case you will not be able to do it, but even if you are, it would not be correct. You should go for code coverage tools, and better unit testing.

    2. You dont want THE equals method, but want a similar method. In this case you can create another method with a similar name in the interface.

提交回复
热议问题