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.