Heim  >  Artikel  >  Java  >  Können wir in Java 9 private Methoden oder private statische Methoden in Schnittstellen definieren?

Können wir in Java 9 private Methoden oder private statische Methoden in Schnittstellen definieren?

WBOY
WBOYnach vorne
2023-09-06 21:29:021202Durchsuche

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

Ja, wir können private Methoden oder private statische Methoden in Schnittstellen in Java 9 haben. Mit diesen Methoden können Sie Coderedundanz entfernen. Private Methoden sind nur innerhalb dieser Schnittstelle nützlich oder zugänglich. Wir können nicht auf private Methoden von einer Schnittstelle auf eine andere Schnittstelle oder Klasse zugreifen oder diese erben.

Syntax

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

Beispiel

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

Ausgabe

<strong>Inside abstract method
Inside private method
Inside private static method
Inside default method
Inside private static method
Inside static method</strong>

Das obige ist der detaillierte Inhalt vonKönnen wir in Java 9 private Methoden oder private statische Methoden in Schnittstellen definieren?. Für weitere Informationen folgen Sie bitte anderen verwandten Artikeln auf der PHP chinesischen Website!

Stellungnahme:
Dieser Artikel ist reproduziert unter:tutorialspoint.com. Bei Verstößen wenden Sie sich bitte an admin@php.cn löschen