Interfaces ใน Java

Java เบื้องต้นสำหรับการเขียนโปรแกรมเชิงวัตถุ

Sani Yusuf

Lead Software Engineering Content Developer

ข้อจำกัดของการสืบทอด

  • การสืบทอดจะส่งต่อสมาชิกทั้งหมด
  • ไม่สามารถเลือกสืบทอดเฉพาะบางสมาชิกได้

  // Car class   
  class Car {
    // Battery capacity is only applicable
    // to electric cars
    public int batteryCapacity;

    void drive() {

    }  
  }


  // Toyata class
  class Toyota extends Car {  
    void drive(){

    }           
  }


// Man class public static class Main { public static void main(String[] args) { Toyota myToyota = new Toyota(); // All cars will inherit the "batteryCapacity" // even if they are not electric cars System.out.println( myToyota.batteryCapacity); // Not applicable } }
Java เบื้องต้นสำหรับการเขียนโปรแกรมเชิงวัตถุ

การสร้าง Interface

  • Interface ช่วยให้เลือกสืบทอด property และเมธอดได้
  • คลาสใช้ interface ด้วยคีย์เวิร์ด implements

  // ElectricCar Interface 
  interface ElectricCar {

  }





  // Tesla implementing the
  // ElectricCar interface
  class Tesla implements ElectricCar {

  }








Java เบื้องต้นสำหรับการเขียนโปรแกรมเชิงวัตถุ

การเพิ่ม Property ให้ Interface

  • Property ใช้รูปแบบ UPPER_SNAKE_CASE ตามข้อตกลง
  • ต้องกำหนดค่าทันทีและไม่สามารถเปลี่ยนแปลงได้
  • Property มีคุณสมบัติเป็น public static final โดยปริยาย

  interface ElectricCar {
    // Implictly public static final
    // Cannot be changed
    int BATTERY_CAPACITY = 310;

  }




Java เบื้องต้นสำหรับการเขียนโปรแกรมเชิงวัตถุ

การเพิ่มเมธอดใน Interface

  • Interface มักใช้เพื่อกำหนดเมธอด
  • เมธอดเป็น abstract โดยค่าเริ่มต้น ไม่มีโค้ด implementation
  • Interface สามารถมีเมธอด concrete ที่มีโค้ด implementation ได้
  • เมธอด abstract ทั้งหมดต้องถูก implement ในคลาสย่อย
  interface ElectricCar {
    // Implictly public static final
    // Cannot be changed
    int BATTERY_CAPACITY = 310;


// This is an abstract method by default void charge();
// This is a concrete method void autoPark() { }
}
class Tesla implements ElectricCar { // Must be implemented public void charge() { } }
Java เบื้องต้นสำหรับการเขียนโปรแกรมเชิงวัตถุ

มาฝึกกันเถอะ!

Java เบื้องต้นสำหรับการเขียนโปรแกรมเชิงวัตถุ

Preparing Video For Download...