Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Java

Default method trong interface Java 8


Java 8 giới thiệu khái niệm default method implementation trong interface. Khả năng này thêm vào để tương thích ngược (backward compatibility) để interface cũ tận dụng lambda expression của Java 8.

Ví dụ, interface List hoặc Collection không có khai báo method forEach. Thêm method đó sẽ phá vỡ collection framework. Java 8 giới thiệu default method để List/Collection có triển khai mặc định forEach, class triển khai không cần implement lại.

Ví dụ

public class Java8Tester {
    public static void main(String args[]) {
        Vehicle vehicle = new Car();
        vehicle.print();
    }
}
interface Vehicle {
    default void print() {
        System.out.println("I am a vehicle!");
    }
    static void blowHorn() {
        System.out.println("Blowing horn!!!");
    }
}
interface FourWheeler {
    default void print() {
        System.out.println("I am a four wheeler!");
    }
}
class Car implements Vehicle, FourWheeler {
    public void print() {
        Vehicle.super.print();
        FourWheeler.super.print();
        Vehicle.blowHorn();
        System.out.println("I am a car!");
    }
}

Kết quả

I am a vehicle!
I am a four wheeler!
Blowing horn!!!
I am a car!