An interface in Java is similar to a class, but it only contains abstract methods and fields modified by final and static.
Suppose we are using an interface and have implemented all the abstract methods in the interface, and then added new methods later. Then all classes using that interface will not work unless you implement the newly added method in every class.
To solve this problem, Java8 introduced default methods.
Default method is also known as defense method or virtual extension method. You can define a default method using the default keyword as follows:
default void display() { System.out.println("This is a default method"); }
Once a default implementation is written for a specific method in an interface, it is There is no need to implement it in the class.
The following Java example demonstrates the use of default methods in Java.
Online Demonstration
interface sampleInterface{ public void demo(); default void display() { System.out.println("This is a default method"); } } public class DefaultMethodExample implements sampleInterface{ public void demo() { System.out.println("This is the implementation of the demo method"); } public static void main(String args[]) { DefaultMethodExample obj = new DefaultMethodExample(); obj.demo(); obj.display(); } }
This is the implementation of the demo method This is a default method
The above is the detailed content of What is the use of default methods in Java?. For more information, please follow other related articles on the PHP Chinese website!