The default Java method introduced from Java 8 is to enable the ability to extend, improve an existing interface without breaking the previously implemented interface. How is it in details? Let’s learn together in this tutorial!
OK, let’s start with the following example.
For example, now I have an interface like this:
1 2 3 4 5 |
package com.huongdanjava; public interface SayHello { void say(); } |
A class implementing the SayHello interface on:
1 2 3 4 5 6 7 8 9 10 |
package com.huongdanjava; public class SayHelloImpl implements SayHello { @Override public void say() { System.out.println("Hello"); } } |
And the class uses:
1 2 3 4 5 6 7 8 9 |
package com.huongdanjava; public class Example { public static void main(String[] args) { SayHello sayHello = new SayHelloImpl(); sayHello.say(); } } |
Result:
Now, what happen when I would like to extend the SayHello interface by adding a new method like this:
1 2 3 4 5 6 |
package com.huongdanjava; public interface SayHello { void say(); void print(); } |
At this point, a compile error will appear in the SayHelloImpl class:
Assume that we cannot edit the SayHelloImpl class because it is currently being used somewhere in our application. So what is the solution here?
This is why the default method in the interface is introduced from Java 8 onwards. With the default method, we can add more methods to any interface with the underlying implementation, which makes it possible to extend or refine the interface without breaking the existing system.
In the example above, we can use the default method with the print() method:
1 2 3 4 5 6 7 8 9 10 |
package com.huongdanjava; public interface SayHello { void say(); default public void print() { System.out.println("Print Hello"); } } |
Result: