5.1 What is Polymorphism?
Polymorphism is derived from Greek words: poly (many) and morph (forms). In OOP, it refers to the capability of a single entity, interface, or method signature to manifest different behaviors depending on the runtime context or object type.
Polymorphism decouples client code from specific concrete implementations, allowing developers to write flexible, extensible programs that can ingest new subclass variations without modifying existing business logic.
5.2 Compile-Time Polymorphism (Static Binding)
Compile-Time Polymorphism (also known as Static Binding or Early Binding) occurs when the compiler determines precisely which method or operator implementation to invoke during compilation.
Mechanisms
- Method Overloading: Defining multiple methods in the same class that share the identical method name but possess distinct parameter signatures (differing in argument count, data types, or parameter sequence). Note: varying the return type alone does NOT constitute valid overloading.
- Operator Overloading: In languages such as C++ and Python, developers can redefine native operators (e.g.
+,==,<<) to perform intuitive mathematical or formatting operations on user-defined objects.
5.3 Run-Time Polymorphism (Dynamic Binding)
Run-Time Polymorphism (also known as Dynamic Binding or Late Binding) occurs when the specific method implementation to execute cannot be determined until program runtime, resolved dynamically based on the concrete heap object type rather than the reference pointer type.
Dynamic Method Dispatch & Virtual Tables (vtable)
When a parent class reference holds a child object (e.g., Animal a = new Dog(); a.sound();), the compiler generates a virtual call instruction. At runtime, the runtime environment inspects the object's internal virtual pointer (vptr) which indexes into the class's Virtual Method Table (vtable) to resolve the overridden Dog.sound() method.
Figure 5.1: Static binding binds methods at compile time via parameter signatures; Dynamic binding resolves overridden calls at runtime based on actual heap instance type.