Java Programming to Interfaces using Static Methods With Examples

In this quick tutorial, we would understand how static methods on interfaces helps us design better code and support the basic design principle: “Program to an interface, not an implementation”. You can find basic details of static methods at java 8 interface changes. Let’s get started with programming to interfaces design principle.

Java Programming to Interfaces

This has been one of the most basic design principles. We should always use interfaces to effectively enforce development contracts while maintaining loose coupling of code.

In Java we have seen several Collection classes follow these principles, where the concrete implementation only exposes the methods they implement from the interfaces, leaving the rest of the implementation in the private methods.

Problem with programming to interface implementation

Let’s introduce an interface SuperHeros which gives us list of characters.

There are many comic studios and each studio would have their own concrete implementation.

The customers/client would use the code as below to write program against interfaces.

What this does is that it inherently ties down the client code with concrete implementation and then it becomes difficult to change the concrete implementations later as this has already been exposed to the clients.

Even though we have interfaces, but we have provided our concrete implementation details to the customer and broken the design principle: Program to an interface, not an implementation. So how do we fix it and make it better?

Java 8 static methods on interfaces

Java 8 brought in a lot of new features and one of them is static method on interfaces. This very interesting and important feature is mostly overlooked by the developer community.

In order to follow our design principle we would introduce static methods which are static factories to create an instance of the Concrete Implementation of the Superheroes. Let’s add the static method to the interfaces:

Additionally make your concrete implementations non public. Now the customers/client would use the code as:

Now with help of static methods we were able to write static factories for our SuperHeros implementations.

Limitation: This approach can be applied only when you have control over the interface, if it’s a third party interface then it won’t work and you are better off with the general approach.

Summary

In this quick tutorial we learnt how to program to interfaces and how a static method in interfaces helps us achieve this.

And to wrap up, you’ll find the source code to this article on Github.

By admin

Leave a Reply

%d bloggers like this: