Home > Java > javaTutorial > body text

What is the use of default methods in Java?

WBOY
Release: 2023-08-20 21:37:54
forward
894 people have browsed it

What is the use of default methods in Java?

An interface in Java is similar to a class, but it only contains abstract methods and fields modified by final and static.

  • It is the specification of method prototype. Whenever you need to instruct programmers or make a contract about how a type's methods and fields should be, you define an interface.
  • If you want your class to follow a certain specification, you need to implement the required interface and provide concrete implementations for all abstract methods in the interface.
  • If you do not provide implementations of all abstract methods in the interface, a compile-time error will be generated.

What happens if a new method is added to the interface?

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

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");      
}
Copy after login

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.

Example

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();      
   }
}
Copy after login

Output

This is the implementation of the demo method
This is a default method
Copy after login

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!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template