Mixin by Interface Default Method in Java 8

In Java 8, the feature of interface Default Method was introduced.

Java 8 introduces “Default Method” or (Defender methods) new feature, which allows developer to add new methods to the interfaces without breaking the existing implementation of these interfaces. It provides flexibility to allow interface define implementation which will use as default in the situation where a concrete class fails to provide an implementation for that method.

This is a very interesting feature and also very useful. With it, we can implement kind of Mixin. Let’s see following case.

Before Java 8

In a system, there is real dog and robot dog, both of them can bark. Before Java 8, we may have the following interface and classes.

Maybe you already see the problem. Dog and RobotDog have the same implementation of method bark(). It’s duplication. It’s not easy to fix this problem, since Dog and RobotDog have different parent classes. RobotDog is not a Dog but it can bark. In Java, there is no multiple inheritance.

With Default Method in Java 8

With default method, the implementation can be more elegant. See the following code.

As you can see, the same logic can easily be extracted into another interface and the implementation of Dog and RobotDog looks simpler.

How about making a RobotDog flying? It’s simple and there can have different options of flying.

Now I have a RobotDog, which can bark as a dog and fly as a bird!