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 theinterfaces
without breaking the existing implementation of theseinterfaces
. It provides flexibility to allowinterface
define implementation which will use as default in the situation where a concreteclass
fails to provide an implementation for thatmethod
.
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
interface Barkable { void bark(); } // both Dog and RobotDog bark similar. class Dog extends Animal implements Barkable { public void bark() { System.out.println("Wang..."); } } class RobotDog extends Robot implements Barkable { public void bark() { System.out.println("Wang..."); } } |
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
interface Barkable { void bark(); } interface BarkLikeADog extends Barkable { default void bark() { System.out.println("Wangwang..."); } } class Dog extends Animal implements BarkLikeADog { } class RobotDog extends Robot implements BarkLikeADog { } |
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
interface Flyable { void fly(); } interface FlyLikeARocket extends Flyable { default void fly() { System.out.println("Engine starting..."); } } interface FlyLikeABird extends Flyable { default void fly() { System.out.println("Wing waving..."); } } class RobotDog extends Robot implements BarkLikeADog, FlyLikeABird { } |
Now I have a RobotDog, which can bark as a dog and fly as a bird!