Home > Java > javaTutorial > body text

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

PHPz
Release: 2023-09-07 13:49:02
forward
721 people have browsed it

在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>
Copy after login

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

Output

<strong>Tutorialspoint
Tutorialspoint</strong>
Copy after login

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!

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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!