Skip to content

HowProgrammingWorks/Polymorphism

Repository files navigation

Polymorphism

Polymorphism classification

  1. Ad-hoc polymorphism - Functions or operators behave differently based on argument types
  • Function and method overloading - Multiple functions with same name, different signatures
  • Operator overloading - Custom behavior for built-in operators: 3-operator.cpp
  • Type-class polymorphism - Ad-hoc polymorphism via type constraints (e.g. Haskell type classes, Rust traits)
  • Coercion polymorphism - Implicit or explicit type conversions: 4-coercion.js
  1. Subtype polymorphism - Objects of derived types can be used where base types are expected
  • Class inheritance - IS-A relationship via base classes: 5-abstract.ts
  • Interface / protocol polymorphism - Contracts that types must implement: 6-protocol.js
  • Structural (duck typing) polymorphism - Compatibility based on structure, not explicit inheritance: 6-protocol.js
  1. Parametric polymorphism - Code written generically to work with any type
  • Generic functions - Functions parameterized by types: JS 9-generics.ts
  • Generic data structures - Data structures parameterized by types: JS TS a-generics.js
  1. Dispatch mechanisms - How the runtime selects which method to call
  • Dynamic dispatch - Method chosen at runtime based on object type: 7-dynamic.js
  • Virtual functions and methods - Base class methods overridable by derived classes: 8-virtual.cpp
  • Multiple or multimethod dispatch - Method chosen based on multiple argument types