DEV Community

Cover image for Java Interfaces Default Methods
FIROUD-Reda
FIROUD-Reda

Posted on

Java Interfaces Default Methods

In an application where an interface has one or multiple implementations, if we add a method to the interface, all of its implementations will be forced to implement it

But using default interface methods, we can add new methods to an interface that are automatically available in the implementations. Therefore, there’s no need to modify the implementing classes.

Let’s see an example

Image description

Here, we have our Animal interface containing two default methods, "sleep" and "wake up." Now, let's implement it in two classes, "Cat" and "Bird."

Cat class:

Image description

Bird class:

Image description

Now, as you can see, we did not implement either of the two default methods in the “Cat” and “Bird” classes. However, as we can observe in our main method, these default methods are available in both classes.

Image description

So far so good . However, as you might have already guessed, this could lead to a big problem if we implement multiple interfaces with the same default method (the multiple inheritance dilemma v2.0 😅).

But don’t worry, the Java team has you covered. Let’s see an example. We’ll add a new interface called “Mammal” and implement it in our “Cat” class.

Image description

Now that our Cat class implements both the Mammal and Animal interfaces, it might get confused about which default method to use, and our application will raise the following error:

Image description

To fix this error, we should override the method and either create a new implementation of our own. In this implementation, if we want, we can basically call one of the old implementations explicitly using the super keyword. This allows us to specify which implementation to use and resolve the ambiguity.

Case 1 : Simple new implementation

Image description

Case 2 : as you may see I called both implementations to show you that it is possible , or you may choose the one that suits you

Image description

I hope you now have a clear understanding of what default methods are, and thank you for reading.

Akihiki

Top comments (0)