Skip to content

多态

一句话解释

多态平均值相同操作能 behave differently depending on 类型的 对象它 是 applied 到.

用大白话说

Polymorphism means "许多表单." In programming, it means you can use the same method name or operator on different types of objects, and each one responds in its own way. The calling code does not need to know which specific type it is dealing with.

For example, a speak() method on a Dog returns "Woof" and on a Cat returns "Meow." You can loop over a list of animals and call speak() on each — each one makes its own sound. The loop does not need to know whether each animal is a dog or cat.

Polymorphism simplifies code: instead of writing 如果 (animal 是 Dog) woof(); else 如果 (animal 是 Cat) meow();, you just call animal.speak() and each type handles it its own way. This is a core principle of object-oriented programming.

示例

javascript
class Dog { speak() { return "Woof"; } }
class Cat { speak() { return "Meow"; } }
class Cow { speak() { return "Moo"; } }

const animals = [new Dog(), new Cat(), new Cow()];
animals.forEach(a => console.log(a.speak()));
// Woof, Meow, Moo

每个 animal 类型有 它的 own speak() 方法. 循环 calls speak() on 每个不使用 knowing 特定类型 — 多态 handles difference.

相关术语

相关资源

相关课程

解读错误信息

用大白话解释常见错误——什么意思、为什么发生、如何修复。

查看错误

← 返回术语表