อินเทอร์เฟซ ใน Java นั้นคล้ายกับคลาส แต่มีเฉพาะเมธอดและฟิลด์ที่เป็นนามธรรมซึ่งเป็นขั้นสุดท้ายและเป็นสแตติก
เนื่องจากมีการใช้เมธอดสแตติก Java8 และเมธอดเริ่มต้นในอินเทอร์เฟซ แตกต่างจากวิธีการนามธรรมอื่น ๆ วิธีการเหล่านี้สามารถมีการใช้งานเริ่มต้นได้ หากคุณมีวิธีการเริ่มต้นในอินเทอร์เฟซ ไม่จำเป็นต้องแทนที่ (ระบุเนื้อหา) ในคลาสที่ใช้อินเทอร์เฟซนี้อยู่แล้ว
กล่าวโดยย่อ คุณสามารถเข้าถึงวิธีการเริ่มต้นของอินเทอร์เฟซโดยใช้วัตถุของคลาสที่นำไปใช้
ตัวอย่าง
interface MyInterface{
public static int num = 100;
public default void display() {
System.out.println("display method of MyInterface");
}
}
public class InterfaceExample implements MyInterface{
public static void main(String args[]) {
InterfaceExample obj = new InterfaceExample();
obj.display();
}
} ผลลัพธ์
display method of MyInterface
การแทนที่วิธีการเริ่มต้น
คุณสามารถแทนที่เมธอดดีฟอลต์ของอินเทอร์เฟซจากคลาสการนำไปใช้
ตัวอย่าง
interface MyInterface{
public static int num = 100;
public default void display() {
System.out.println("display method of MyInterface");
}
}
public class InterfaceExample implements MyInterface{
public void display() {
System.out.println("display method of class");
}
public static void main(String args[]) {
InterfaceExample obj = new InterfaceExample();
obj.display();
}
} ผลลัพธ์
display method of class