Home  >  Article  >  Java  >  What are the rules for private methods in interfaces in Java 9?

What are the rules for private methods in interfaces in Java 9?

WBOY
WBOYforward
2023-08-31 12:57:111333browse

在Java 9中,接口中的私有方法有哪些规则?

Java 9 adds privatemethodsnew features in interface. Private methods can be defined using the private modifier. We can add private and privatestaticmethods in the interface of

Java 9

Rules for private methods in interfaces:

  • Having the body of a private method in the interface means that we cannot declare it as a normal abstract method as we usually do in interfaces. If we try to declare a private method without a body, then it may throw an error saying "This method requires a body and not a semicolon ".
  • We cannot use private and abstract modifiers simultaneously in an interface.
  • If we want to access a private method from a static method in the interface, then the method can be declared as Private static method because we cannot make a static reference to a non-static method .
  • A A private static method used in a non-static context means that it can be called from the default method in the interface.

Syntax

<strong>interface <interface-name> {
   private methodName(parameters) {
      // some statements
   }
}</strong>

Example

interface TestInterface {
   <strong>default </strong>void methodOne() {
      System.out.println("This is a Default method One...");
      printValues(); // calling a private method
   }
   <strong>default </strong>void methodTwo() {
      System.out.println("This is a Default method Two...");
      printValues(); // calling private method...
   }
   <strong>private </strong>void <strong>printValues</strong><strong>()</strong> { <strong>// private method in an interface
</strong>      System.out.println("methodOne() called");
      System.out.println("methodTwo() called");
   }
}
public class PrivateMethodInterfaceTest implements TestInterface {
   public static void main(String[] args) {
      TestInterface instance = new PrivateMethodInterfaceTest();
      instance.methodOne();
      instance.methodTwo();
   }
}

Output

<strong>This is a Default method One...
methodOne() called
methodTwo() called
This is a Default method Two...
methodOne() called
methodTwo() called</strong>

The above is the detailed content of What are the rules for 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