Last Updated: 12 October, 2023
Before JDK 1.8, Inteface can only have abstract methods, and all the abstract methods must be overridden in the implementing class. These interface methods are by default public and abstract.
Java 8 introduced a feature called default method, which creates a default method inside an interface with a body. We can have one or more default methods inside the interface.
Default methods are non-abstract methods in Java.
We can create a default method in Java by simply adding the default keyword to the method signature and providing the default implementation that can be used, overridden, or ignored without causing problems for existing classes that have implemented an interface.
The default method is one of the strong features of Java 8. It can be used to improve the flexibility and extensibility of interfaces.
Let's see the syntax of the default method implementation inside an interface.
Syntax:
Here is an example of a default method:
Here, the Printer class has two default methods with their own default implementation. The OutputPrinter class implements the Printer interface, overrides both the default methods, and provides its own implementation.
Output
Hello Guys... This is default first method.
show method overridden in OutputPrinter class
Print method.
That's all guys, hope this Java article is helpful for you.
Happy Learning... 😀
feedback@javabytechie.com
Related Articles