多态就是同一个接口,使用不同的实例而执行不同操作

多态性(Polymorphism)是面向对象编程的一个重要概念

// 接口
interface SoundMaker {
    void makeSound();
}

// 实现接口的基类
class Animal implements SoundMaker {
    @Override
    public void makeSound() {
        System.out.println("Animal makes a sound");
    }
}

// 实现接口的派生类
class Dog implements SoundMaker {
    @Override
    public void makeSound() {
        System.out.println("Dog barks");
    }
}

class Cat implements SoundMaker {
    @Override
    public void makeSound() {
        System.out.println("Cat meows");
    }
}


public class Main {
    public static void main(String[] args) {
        // 使用接口类型的引用指向实现类的对象
        SoundMaker myDog = new Dog();
        SoundMaker myCat = new Cat();

        // 调用 makeSound 方法
        myDog.makeSound(); // 运行时调用 Dog 类的 makeSound 方法
        myCat.makeSound(); // 运行时调用 Cat 类的 makeSound 方法
    }
}

  

posted on 2023-12-12 15:43  黑逍逍  阅读(1)  评论(0编辑  收藏  举报