Summary
Polymorphism, a core OOP principle, enables an action or method to behave differently depending on the object it operates on. It manifests in three primary forms: overloading, overriding, and dynamic method binding. Overloading involves methods sharing a name but differing in parameter count or types, allowing context-specific behavior. Overriding occurs when a subclass redefines a method with an identical signature, ensuring the subclass's implementation is used. Dynamic method binding further extends this by resolving method calls to the correct subclass implementation at runtime, even when referenced through a parent type.
多态性 是某个动作或 方法 能够根据其作用的对象执行不同操作的能力。这是面向对象编程的第三个基本原则。 重载、 重写 和 动态方法绑定 是多态性的三种类型。
重载方法 是指具有相同 名称签名 但参数数量不同或参数类型不同的方法。例如,“旋转”一个数字可能意味着增加它,“旋转”一张图像可能意味着将其旋转90度。通过定义一个方法来处理每种类型的参数,您可以控制所需的效果。
重写方法 是在继承类或子类中重新定义的方法。它们具有 相同 的签名,并使用子类定义。
动态(或后期)方法绑定 是指程序能够在 运行时 解析对子类方法的引用。例如,假设基于Animal抽象类创建了三个子类(Cow、Dog和Snake),每个子类都有自己的speak()方法。尽管每个方法引用都是指向Animal(但不存在animal对象),但程序将在运行时解析正确的方法引用。
No comment for this article.