Sobes.tech
Junior — Middle

Can you list the types of polymorphism encountered in object-oriented programming?

sobes.tech AI

Answer from AI

In object-oriented programming (OOP), several types of polymorphism are distinguished:

  1. Subtype (Subtype Polymorphism) — allows objects of different classes related by inheritance to use the same interface. For example, a method accepting a base class can work with objects of derived classes.

  2. Parametric (Parametric Polymorphism) — implemented through generics, where functions or classes operate with different data types without changing the code.

  3. Ad-hoc (Ad-hoc Polymorphism) — function or operator overloading, where a single function can have multiple implementations with different parameters.

Example in C#:

// Subtype polymorphism
class Animal { public virtual void Speak() { Console.WriteLine("Animal sound"); } }
class Dog : Animal { public override void Speak() { Console.WriteLine("Bark"); } }

// Parametric polymorphism
class Box<T> { public T Value; }

// Ad-hoc polymorphism (overloading)
void Print(int x) { Console.WriteLine(x); }
void Print(string s) { Console.WriteLine(s); }

These types of polymorphism allow writing flexible and extensible code.

Can you list the types of polymorphism encountered in… - sobes.tech