多态

54 阅读2分钟

scala

class Animal() {
    def eating(): Unit = {
        println("Animal eating")
    }
}

// Dog 继承 Animal
class Dog extends Animal() {
    override def eating(): Unit = {
        println("我是狗,我大口大口地吃")
    }
}

// Cat 继承 Animal
class Cat extends Animal() {
    override def eating(): Unit = {
        println("我是猫,我小口小口地吃")
    }
}

// 多态测试
def test(animal: Animal): Unit = {
    animal.eating()
}

def main(args: Array[String]): Unit = {
    val cat = new Cat()
    val dog = new Dog()
    
    test(cat)  // 传入子类的对象
    test(dog)
}

执行结果

text

我是猫,我小口小口地吃
我是狗,我大口大口地吃

多态的核心概念

1. 什么是多态?

多态:同一个操作作用于不同的对象,可以有不同的解释和不同的执行结果。

2. 多态的三个必要条件

  • 继承:Dog 和 Cat 都继承自 Animal
  • 重写:子类重写父类的 eating() 方法
  • 父类引用指向子类对象test(animal: Animal) 可以接受任何 Animal 子类

3. 多态的优势

编译时类型 vs 运行时类型

scala

def test(animal: Animal): Unit = {
    // 编译时类型:Animal(编译器只知道是Animal)
    // 运行时类型:可能是 Cat、Dog 或其他 Animal 子类
    animal.eating()  // 运行时根据实际对象类型调用对应方法
}

多态的实际应用场景

  1. 框架设计:定义接口,让用户实现具体逻辑
  2. 插件系统:统一的插件接口,不同的插件实现
  3. 算法抽象:同一算法适用于不同数据类型
  4. 事件处理:统一的事件接口,不同的事件处理器

总结

多态是面向对象编程的三大特性之一(封装、继承、多态),它让代码:

  • 更灵活:易于扩展新功能
  • 更简洁:统一处理逻辑
  • 更易维护:减少条件判断语句

在你的例子中,test 函数不需要知道具体是 Cat 还是 Dog,只需要知道它是 Animal,这就是多态的威力!