Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Java

ทำไม Interface ไม่สามารถ Implement อีก Interface ใน Java ได้?

Interface ไม่สามารถ implement อีก interface ใน Java ได้

  • Interface ใน Java 本质上是一種特殊的 class 像 classes interfaces มี methods และ variables ต่างจาก classes interfaces เสมอเป็น completely abstract
  • Interface ถูกกำหนดเหมือน class เว้นแต่ keyword interface แทน class variables ที่ประกาศใน interface เป็น static และ final และ methods ที่กำหนดใน interface เป็น public abstract methods
  • Interface สามารถ extend interfaces ได้หลายตัว แต interface หนึ่ง ไม่สามารถ implement อีก interface ได้ เพราะถ้า implement interface ใดๆ เมธอดของมันต้องถูก defined และ interface ไม่มี definition ของเมธอดใดๆ
  • ถ้าลอง implement interface ด้วยอีก interface จะเกิด compile-time error ใน Java

ตัวอย่าง

interface MainInterface {
    void mainMethod();
}
interface SubInterface extends MainInterface { // If we put implements keyword in place of extends, compiler throws an error.
    void subMethod();
}
class MainClass implements MainInterface {
    public void mainMethod() {
        System.out.println("Main Interface Method");
    }
    public void subMethod() {
        System.out.println("Sub Interface Method");
    }
}
public class Test {
    public static void main(String args[]) {
        MainClass main = new MainClass();
        main.mainMethod();
        main.subMethod();
    }
}

ผลลัพธ์

Main Interface Method
Sub Interface Method