ในการใช้วิธีสแตติกในอินเทอร์เฟซ รหัส Java มีดังต่อไปนี้ -
ตัวอย่าง
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);
}
} ผลลัพธ์
In the newly created static method In the override method
มีการกำหนดอินเทอร์เฟซภายในซึ่งมีการกำหนดฟังก์ชันแบบคงที่ ฟังก์ชันอื่นที่ชื่อว่า 'method_override' ถูกกำหนดโดยไม่มีเนื้อหา อินเทอร์เฟซนี้ใช้งานโดยคลาสอื่นที่ชื่อ 'Demo_interface' ภายในคลาสนี้ มีการกำหนดฟังก์ชันหลัก และสร้างอินสแตนซ์ของ 'Demo_interface' นี้ด้วย ฟังก์ชันสแตติกถูกเรียกใช้ในอินสแตนซ์นี้ และถัดไป ฟังก์ชัน 'method_override' จะถูกเรียกใช้ในอินสแตนซ์นี้ มีการเขียนข้อกำหนดการแทนที่ ซึ่งอยู่ภายใต้การกำหนด 'method_override' ฟังก์ชันนี้เพียงแค่พิมพ์สตริงบนคอนโซล