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
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:
Bird class:
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.
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.
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:
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
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
I hope you now have a clear understanding of what default methods are, and thank you for reading.
Akihiki
Top comments (0)