Home > Java > javaTutorial > body text

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

WBOY
Release: 2023-08-31 12:57:11
forward
1332 people have browsed it

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

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

Output

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

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!

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