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

ความแตกต่างระหว่าง Default Method และ Static Method ใน Java 8 Interface

Java 8 เปิดให้ Interface มี **Method Body** ได้ 2 แบบ: default และ static มีจุดประสงค์และพฤติกรรมต่างกัน

ตารางเปรียบเทียบ

ลำดับหัวข้อStatic Interface MethodDefault Method
1พื้นฐานเป็น method ของ **Interface class** เอง ไม่ผูกกับ instanceเป็น method ของ **Implementing class** (instance method)
2Keywordstaticdefault
3Override**ไม่ได้** (static method ไม่ override - hiding)**ได้** (และควร override เพื่อ custom behavior)
4การเรียกใช้ผ่าน Interface name เท่านั้น InterfaceName.method()ผ่าน Interface หรือ Instance instance.method()
5เข้าถึง thisไม่ได้ (ไม่มี instance)ได้ (this = implementing instance)
6Inheritanceไม่สืบทอด (Sub-interface ต้อง declare ใหม่)สืบทอดได้ (Sub-interface override ได้)
7Use CaseUtility/Helper methods, Factory methodsCommon implementation, Backward compatibility
8Multiple Implementationไม่เกี่ยวข้อง (class ไม่ implement static)Diamond problem - ต้อง override เองถ้ามีหลาย interface

ตัวอย่าง: Default และ Static Method ใน Interface

interface Vehicle {
    // Abstract method - ต้อง implement
    void startEngine();
    
    // Default method - มี body, override ได้
    default void honk() {
        System.out.println("Beep beep! (default)");
    }
    
    // Default method อีกตัว
    default void checkFuel() {
        System.out.println("Checking fuel... " + getFuelLevel());
    }
    
    // Static method - utility, เรียกผ่าน Interface
    static void printManual() {
        System.out.println("=== Vehicle Manual ===");
        System.out.println("1. Start engine");
        System.out.println("2. Drive safely");
    }
    
    // Private method (Java 9+) - helper สำหรับ default methods
    private int getFuelLevel() {
        return 75; // mock
    }
    
    // Private static method (Java 9+)
    private static String getManufacturer() {
        return "Generic Motors";
    }
}

// Implementation
class Car implements Vehicle {
    @Override
    public void startEngine() {
        System.out.println("Car engine started - Vroom!");
    }
    
    // Override default method
    @Override
    public void honk() {
        System.out.println("HONK HONK! (Car horn)");
    }
}

class Motorcycle implements Vehicle {
    @Override
    public void startEngine() {
        System.out.println("Motorcycle engine started - Brrrrrum!");
    }
    // ไม่ override honk() → ใช้ default
}

public class InterfaceMethodsDemo {
    public static void main(String[] args) {
        Vehicle car = new Car();
        Vehicle bike = new Motorcycle();
        
        // Instance methods (default/abstract)
        car.startEngine();    // Car engine started - Vroom!
        car.honk();           // HONK HONK! (Car horn)
        car.checkFuel();      // Checking fuel... 75
        
        bike.startEngine();   // Motorcycle engine started - Brrrrrum!
        bike.honk();          // Beep beep! (default)
        bike.checkFuel();     // Checking fuel... 75
        
        // Static method - เรียกผ่าน Interface เท่านั้น
        Vehicle.printManual(); 
        // Car.printManual(); // ❌ Compile error! Static method ไม่สืบทอด
        
        // ไม่สามารถเรียก static ผ่าน instance ได้
        // car.printManual(); // ❌ Compile error!
    }
}

Output

Car engine started - Vroom!
HONK HONK! (Car horn)
Checking fuel... 75
Motorcycle engine started - Brrrrrum!
Beep beep! (default)
Checking fuel... 75
=== Vehicle Manual ===
1. Start engine
2. Drive safely

Diamond Problem กับ Default Methods

interface A {
    default void hello() { System.out.println("A"); }
}
interface B {
    default void hello() { System.out.println("B"); }
}

// Class implement ทั้ง 2 interface → Compile Error!
// class C implements A, B { } // Error: duplicate default method

// ต้อง override เอง
class C implements A, B {
    @Override
    public void hello() {
        // สามารถเลือกเรียกได้
        A.super.hello(); // เรียก A's default
        B.super.hello(); // เรียก B's default
        System.out.println("C's own implementation");
    }
}

Private Methods in Interface (Java 9+)

interface MyInterface {
    default void publicMethod1() {
        helper(); // เรียก private method
        System.out.println("Public 1");
    }
    
    default void publicMethod2() {
        helper(); // ใช้ซ้ำ logic
        System.out.println("Public 2");
    }
    
    // Private instance method
    private void helper() {
        System.out.println("Shared helper logic");
    }
    
    // Private static method
    private static void staticHelper() {
        System.out.println("Static helper");
    }
    
    static void staticMethod() {
        staticHelper();
        System.out.println("Static method");
    }
}

สรุป: เมื่อไหร่ใช้อะไร?

  • default: Common behavior ที่ subclass อาจจะ override (เพิ่ม feature โดยไม่ breaking existing implementations)
  • static: Utility methods ที่เกี่ยวข้องกับ interface แต่ไม่ต้องการ state (helper, factory, constants)
  • private (Java 9+): Shared logic ระหว่าง default methods (DRY principle)