Java 8 Interface Default Methods example
15 May 2014
In this article we will cover Java 8 interface default methods.
Java 8 Interface Default Methods
One of the new features introduced in Java 8 consists in interface default methods, also know as Extension Methods.
Interfaces now may also provide default method implementations:
TestInterface.java
package com.byteslounge; public interface TestInterface { default String methodOne(String input){ return "Default methodOne implementation. Input: " + input; } String methodTwo(String input); }
As we can see above, TestInterface is providing a default implementation for method methodOne.
This means that any concrete class that directly implements TestInterface is not required to implement method methodOne:
TestClass.java
package com.byteslounge; public class TestClass implements TestInterface { @Override public String methodTwo(String input) { return "methodTwo implementation. Input: " + input; } }
If methodOne is called against a TestClass instance, the default method defined in TestInterface will be called.
We are obviously still able to override methodOne if we need it:
TestClass.java
package com.byteslounge; public class TestClass implements TestInterface { @Override public String methodTwo(String input) { return "methodTwo implementation. Input: " + input; } @Override public String methodOne(String s) { return "methodOne is overriden!"; } }