The purpose of interfaces continued

后端 未结 13 1399
轮回少年
轮回少年 2020-12-03 02:28

OK so I gather that Interfaces are a way to enforce that an object implements a certain amount of functionality, without having to use inheritance. Kind of like a contract.

13条回答
  •  情深已故
    2020-12-03 02:52

    This isn't really an answer so much as an example that I find helpful when thinking about interfaces, but think about the interface Comparable which requires the method

    public int compareTo(T anotherObject)
    

    The user can implement this however he or she wants. If a Person implements Comparable, for example, the comparison can be based on last name then first name, ignoring capitalization. Or it can be based on age, etc. However the user wants. Implementing this interface is very useful, in that it allows the user to use things like Collections.sort() which require that the elements to be sorted need to be comparable (how else could a comparison be made?)

提交回复
热议问题