Introduction about default method in Java

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:

A class implementing the SayHello interface on:

And the class uses:


Introduction about default method in Java

Now, what happen when I would like to extend the SayHello interface by adding a new method like this:

At this point, a compile error will appear in the SayHelloImpl class:

Introduction about default method in Java

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:

Introduction about default method in Java

Chia sẽ bài viết này ...Share on Facebook
0Tweet about this on Twitter
Share on LinkedIn

Add Comment