Polymorphism, in simple terms, refers to the ability of a function or method to take on different forms or behave differently depending on the context. It allows objects of different types to be treated as objects of a common type. This concept is not exclusive to object-oriented systems but is commonly associated with them.
Polymorphism means having many forms: This implies that a single function or method can have different implementations.
The ability of a message to be displayed in more than one form: In the context of object-oriented programming, a message refers to a method call. The same method name can be used on different objects, and each object’s class determines how the method is executed.
Allows objects with different internal structures to share the same external interface: Objects may have different implementations internally, but they can expose a common interface, enabling them to be used interchangeably.
Operation as a function applied to or by objects in a class: Operations are functions associated with a class. All objects of that class share the same set of operations.
Examples of operations on class Window: Open, close, hide, and redisplay are operations that can be performed on objects of the Window class. All Window objects share these operations.
Behavior of an operation depends on the class of its target: The specific implementation of an operation is determined by the class of the object on which the operation is called.
Object “knows” its class: Each object has information about its class, allowing it to determine the correct implementation of an operation.
Polymorphism in File class with a print operation: The File class might have a print operation, and different subclasses could implement this operation in various ways, such as printing ASCII files, binary files, or digitized picture files.
In terms of applicability:
- Ad-hoc polymorphism: Applies to both traditional and object-oriented programming, where functions can be applied to arguments of different types.
- Universal polymorphism: Specifically, parametric and subtyping polymorphism, is more associated with object-oriented systems. Polymorphic functions are written without specifying a specific type.