Rumah  >  Artikel  >  Java  >  Dalam Java 9, bolehkah kita menggunakan kaedah persendirian dalam antara muka?

Dalam Java 9, bolehkah kita menggunakan kaedah persendirian dalam antara muka?

WBOY
WBOYke hadapan
2023-08-25 12:33:06840semak imbas

在Java 9中,我们可以在接口中使用私有方法吗?

Ya, memandangkan Java9 anda boleh menggunakan kaedah peribadi dalam antara muka.

Contoh

interface MyInterface {
   public abstract void demo();
   public default void defaultMethod() {
      privateMethod();
      staticPrivateMethod();
      System.out.println("This is a default method of the interface");
   }
   public static void staticMethod() {
      staticPrivateMethod();
      System.out.println("This is a static method of the interface");
   }
   private void privateMethod(){
      System.out.println("This is a private method of the interface");
   }
   private static void staticPrivateMethod(){
      System.out.println("This is a static private method of the interface");
   }
}
public class InterfaceMethodsExample implements MyInterface {
   public void demo() {
      System.out.println("Implementation of the demo method");
   }
   public static void main(String[] args){
      InterfaceMethodsExample obj = new InterfaceMethodsExample();
      obj.defaultMethod();
      obj.demo();
      MyInterface.staticMethod();
   }
}

Output

This is a private method of the interface
This is a static private method of the interface
This is a default method of the interface
Implementation of the demo method
This is a static private method of the interface
This is a static method of the interface

Atas ialah kandungan terperinci Dalam Java 9, bolehkah kita menggunakan kaedah persendirian dalam antara muka?. Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!

Kenyataan:
Artikel ini dikembalikan pada:tutorialspoint.com. Jika ada pelanggaran, sila hubungi admin@php.cn Padam