Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Java

Phương thức static trong Interface trong Java


Để triển khai phương thức static trong Interface, mã Java như sau:

Ví dụ

interface my_interface{    static void static_fun(){       System.out.println("In the newly created static method");    }    void method_override(String str); } public class Demo_interface implements my_interface{    public static void main(String[] args){       Demo_interface demo_inter = new Demo_interface();       my_interface.static_fun();       demo_inter.method_override("In the override method");    }    @Override    public void method_override(String str){       System.out.println(str);    } }

Kết quả

In the newly created static method In the override method

Một interface được định nghĩa, bên trong có hàm static. Hàm method_override được định nghĩa không có thân. Interface này được triển khai bởi lớp Demo_interface. Trong lớp này, hàm main được định nghĩa, thể hiện của Demo_interface được tạo. Hàm static được gọi trên thể hiện này, tiếp theo hàm method_override được gọi. Chỉ định @Override, dưới đó method_override được định nghĩa. Hàm này chỉ in chuỗi ra console.