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

โปรแกรม Java ใช้งาน Multiple Inheritance ด้วย Interface

ในบทความนี้ เราจะเรียนรู้วิธีทำ Multiple Inheritance ในภาษา Java Java ไม่รองรับการสืบทอดหลายคลาสโดยตรง (class ไม่สามารถ extends หลาย class ได้) แต่สามารถทำได้ผ่าน Interface

อัลกอริทึม

  1. เริ่มต้นโปรแกรม
  2. ประกาศ Interface 2 ตัว: My_restaurents, My_journey
  3. สร้างคลาส Holiday implements ทั้ง 2 interface
  4. สร้างวัตถุจากคลาส Holiday เรียกเมธอดจากทั้งสอง interface
  5. จบโปรแกรม

ตัวอย่างที่ 1: ใช้ Interface (แนะนำ)

interface My_restaurents {
    void eat();
}

interface My_journey {
    void travel();
}

class Holiday implements My_restaurents, My_journey {
    public void eat() {
        System.out.println("I am trying this food");
    }
    public void travel() {
        System.out.println("I am trying this route");
    }
}

public class My_trip {
    public static void main(String args[]) {
        Holiday my_schedule = new Holiday();
        my_schedule.eat();
        my_schedule.travel();
    }
}

Output: I am trying this food / I am trying this route

ตัวอย่างที่ 2: ใช้การสืบทอดแบบโซ่ (Chain Inheritance)

class Server {
    void my_frontend() {
        System.out.println("Connection to frontend established successfully");
    }
}

class Java extends Server {
    void my_backend() {
        System.out.println("Connection to backend established successfully");
    }
}

class Connection extends Java {
    void my_database() {
        System.out.println("Connection to database established successfully");
    }
}

public class My_test {
    public static void main(String args[]) {
        Connection my_connection = new Connection();
        my_connection.my_database();
        my_connection.my_backend();
        my_connection.my_frontend();
    }
}

Output: เรียกเมธอดทั้ง 3 ได้ผ่านวัตถุ Connection เดียว

สรุป

  • Interface: รองรับ Multiple Inheritance จริง implements หลาย interface ได้
  • Class Chain: ใช้ extends แบบโซ่ (A extends B, B extends C) เข้าถึงเมธอดทั้งโซ่ได้
  • Java 8+ สามารถใช้ default method ใน interface ได้อีกด้วย