Search code examples
javaoopdesign-patterns

Do interfaces have any purpose besides achieving polymorphism and multiple inheritance?


I am trying to understand what the benefits of using interfaces are so that I can know when and how to use them. Most sources on the internet are relatively surface-level, explaining how interfaces work but not why to use them, and when I look up the titular question, I don't get any results that tell me whether the purpose of interfaces extends beyond polymorphism and multiple inheritances.

My reasoning is that if an interface were inherited by only one class, it would be useless, and when an interface is inherited by multiple classes, it makes no difference unless it is used for polymorphism, and the only thing that makes implementation different from extension is multiple inheritances.

If I knew for sure that their purpose was limited to this, I would have an increased confidence in my design decisions, and if I learned of a purpose outside of this, it would fill a serious gap in my knowledge. I have used the design patterns tag because there is perhaps a design pattern which makes use of interfaces in a way that is distinctly beyond mere polymorphism or multiple inheritances.


Solution

  • if an interface were inherited by only one class, it would be useless

    I agree, but you can read a lot of discussion on this topic in Java Interfaces Methodology: Should every class implement an interface?

    when an interface is inherited by multiple classes, it makes no difference unless it is used for polymorphism

    I agree, it would be silly to implement an interface and then bypass it by invoking its methods directly on the concrete class. The purpose of implementing an interface is to have its abstract methods called, which is polymorphism in action. Since polymorphism is the primary tool of Object Oriented Programming, you could take this statement a step further and say that OOP makes no difference unless it is used for polymorphism.

    the only thing that makes implementation different from extension is multiple inheritances

    No, the primary difference between these Java constructs is that interface implementation facilitates stateless inheritance whereas class extension facilitates stateful inheritance. Java happens to support multiple stateless inheritance and single stateful inheritance. This dichotomy may be considered a mistake.

    Do interfaces have any purpose besides achieving polymorphism and multiple inheritance?

    In practice, yes. You can find interfaces used for other purposes such as constant interfaces or marker interfaces. Whether these practices are advisable has been debated.