Home > Java > javaTutorial > In Java 9, can we define private methods or private static methods in interfaces?

In Java 9, can we define private methods or private static methods in interfaces?

WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB
Release: 2023-09-06 21:29:02
forward
1338 people have browsed it

在Java 9中,我们可以在接口中定义私有方法或私有静态方法吗?

Yes, we can have privatemethodsor private static methods## in interfaces in Java 9 #. You can use these methods to remove code redundancy. PrivateMethods are only useful or accessible within this interface. We cannot access or inherit private methods from one interface to another interface or class.

Syntax

<strong>interface <interface-name> {
   private static void methodName() {
      // some statements
   }
   private void methodName() {
      // some statements
   }
}</strong>
Copy after login

Example

interface Java9Interface {
   public abstract void method1();
   public default void method2() {
      method4();
      method5();
      System.out.println("Inside default method");
   }
   public static void method3() {
      method5();    <strong>//  static method inside other static method</strong>
      System.out.println("Inside static method");
   }
   private void method4() {    <strong>// private method</strong>
      System.out.println("Inside private method");
   }
   private static void method5() {    <strong>// private static method</strong>
      System.out.println("Inside private static method");
   }
}
public class PrivateStaticMethodTest implements Java9Interface {
   @Override
   public void method1() {
       System.out.println("Inside abstract method");
   }
   public static void main(String args[]) {
      Java9Interface instance = new PrivateStaticMethodTest();
      instance.method1();
      instance.method2();
      Java9Interface.method3();
   }
}
Copy after login

Output

<strong>Inside abstract method
Inside private method
Inside private static method
Inside default method
Inside private static method
Inside static method</strong>
Copy after login

The above is the detailed content of In Java 9, can we define private methods or private static methods in interfaces?. For more information, please follow other related articles on the PHP Chinese website!

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