javainterface

Under what circumstances should I use an interface in Java instead of a class in system design?


A good example of when exactly to use interfaces specifically in Java would be ideal and any specific rulings that apply.


Solution

  • Use interfaces to define an application programming contract (blueprint, interface) which "3rd-party" vendors have to fully adhere and implement. This way the end users can just code against the API contract and easily switch of the concrete implementation "under the hoods" without changing the code.

    The JDBC API is an excellent example. It exists of almost only interfaces. The concrete implementations are provided as "JDBC drivers". This enables you to write all the JDBC code independent of the database (DB) vendor. You can just change the JDBC driver without changing any line of Java code (except of any hard coded DB-specific SQL code) whenever you'd like to switch of DB vendor.

    Another example is the Jakarta EE API, it also consists of pretty much interfaces and abstract classes. The concrete implementations are provided as "Jakarta EE application servers" such as WildFly, GlassFish, Liberty, TomEE, etc. This enables you to deploy the web application archive (WAR) to whatever application server you want without changing any line of Java code (except of any server-specific XML configuration files) whenever you'd like to switch of runtime.

    See also: