Java泛型extends能否實(shí)現(xiàn)多態(tài)

小樊
81
2024-09-29 23:00:16

Java泛型中的extends關(guān)鍵字可以實(shí)現(xiàn)多態(tài)。在Java中,多態(tài)是指允許一個(gè)類的引用變量指向另一個(gè)類的對(duì)象。通過使用extends關(guān)鍵字,你可以創(chuàng)建一個(gè)泛型類,該類可以繼承另一個(gè)類或?qū)崿F(xiàn)一個(gè)接口。這樣,你可以使用泛型類來處理不同類型的對(duì)象,同時(shí)保持多態(tài)性。

以下是一個(gè)簡(jiǎn)單的示例,說明如何使用extends關(guān)鍵字實(shí)現(xiàn)多態(tài):

// 定義一個(gè)基類(父類)Animal
class Animal {
    void makeSound() {
        System.out.println("The animal makes a sound");
    }
}

// 定義一個(gè)泛型類Dog,繼承自Animal類
class Dog<T extends Animal> extends Animal {
    // Dog類繼承了Animal類,因此可以實(shí)現(xiàn)多態(tài)
    void fetch() {
        System.out.println("The dog fetches the ball");
    }
}

// 定義一個(gè)泛型類Cat,繼承自Animal類
class Cat<T extends Animal> extends Animal {
    // Cat類繼承了Animal類,因此可以實(shí)現(xiàn)多態(tài)
    void scratch() {
        System.out.println("The cat scratches");
    }
}

public class Main {
    public static void main(String[] args) {
        // 使用泛型類Dog和Cat,它們都繼承自Animal類,因此可以實(shí)現(xiàn)多態(tài)
        Animal myAnimal = new Dog<>();
        myAnimal.makeSound(); // 輸出:The animal makes a sound
        ((Dog) myAnimal).fetch(); // 輸出:The dog fetches the ball

        myAnimal = new Cat<>();
        myAnimal.makeSound(); // 輸出:The animal makes a sound
        ((Cat) myAnimal).scratch(); // 輸出:The cat scratches
    }
}

在這個(gè)示例中,我們定義了一個(gè)基類Animal和兩個(gè)泛型子類DogCat,它們都繼承自Animal類。我們可以使用Animal類型的引用來指向DogCat對(duì)象,從而實(shí)現(xiàn)多態(tài)。

0