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

Giải quyết Diamond Problem bằng default method trong Java

Kế thừa là quan hệ giữa hai class, một class kế thừa thuộc tính class kia. Dùng extends:

public class A extends B { }

Class kế thừa = sub/child class, class được kế thừa = super/parent class. Bản sao thành viên super class tạo trong sub class object → truy cập được cả hai.

Đa kế thừa: một class kế thừa nhiều class. Một child class, n parent class. Java KHÔNG hỗ trợ đa kế thừa (với class).

Vấn đề kim cương (Diamond Problem)

  • Giả sử Java hỗ trợ đa kế thừa
  • Abstract class Sample có abstract method demo()
  • Hai class khác extends Sample và implement demo()
  • Subclass extends cả hai → có 2 method demo() cùng signature
  • Gọi demo() → compiler ambiguous → Diamond Problem

Giải quyết Diamond Problem bằng default method trong Java

Giải pháp Diamond Problem

Dùng default method (Java 8) và interface.

  • Từ Java 8, interface có default method (có implementation mặc định)
  • Không bắt buộc override default method trong class implement
  • Có thể có cùng default method trong 2 interface khác nhau
  • Class implement 2 interface → BẮT BUỘC override default method, chỉ định interface: MyInterface1.super.display() hoặc MyInterface2.super.display()

Ví dụ

interface MyInterface1 {
    public static int num = 100;
    public default void display() {
        System.out.println("display method of MyInterface1");
    }
}

interface MyInterface2 {
    public static int num = 1000;
    public default void display() {
        System.out.println("display method of MyInterface2");
    }
}

public class InterfaceExample implements MyInterface1, MyInterface2 {
    public void display() {
        MyInterface1.super.display();
        // hoặc MyInterface2.super.display();
    }
    
    public static void main(String args[]) {
        InterfaceExample obj = new InterfaceExample();
        obj.display();
    }
}

Đầu ra

display method of MyInterface1
display method of MyInterface2