Home  >  Article  >  Java  >  What are the advantages of private methods in interfaces in Java 9?

What are the advantages of private methods in interfaces in Java 9?

PHPz
PHPzforward
2023-09-07 13:49:02706browse

在Java 9中,接口中私有方法的优势是什么?

In Java 9, interfaces can also have private methods. Apart from static and default methods in Java 8, this is another big change as it allows reusability of public # strong>Code is within the interface itself.

In the interface, it is possible to write common code on multiple default methods, thus generating

code duplication. The introduction of private methods avoids this code duplication.

Advantages of private methods in interfaces

    Avoid code duplication.
  • Ensure code reusability.
  • Improve code readability.
Syntax

<strong>interface interfacename {
   private methodName(parameters) {
      // statements
    }
}</strong>

Example

interface Test {
   default void m1() {
      common();
   }
   default void m2() {
      common();
   }
   private void common() {
      System.out.println("Tutorialspoint");
   }
}
public class PrivateMethodTest implements Test {
   public static void main(String args[]) {
      Test test = new PrivateMethodTest();
      test.m1();
      test.m2();
   }
}

Output

<strong>Tutorialspoint
Tutorialspoint</strong>

The above is the detailed content of What are the advantages of private methods in interfaces in Java 9?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete