Sobes.tech
Junior — Middle

Can you explain the different types of polymorphism in object-oriented programming?

sobes.tech AI

Answer from AI

In object-oriented programming, polymorphism is the ability of objects of different classes to respond to the same messages (methods) in different ways. The main types of polymorphism:

  1. Compile-time (static) polymorphism — determined during compilation.

    • Method overloading: multiple methods with the same name but different parameters.
    • Operator overloading — limited in C#, but possible for some operators.
  2. Runtime (dynamic) polymorphism — determined during execution.

    • Method overriding: a subclass provides its own implementation of a base class method.
    • Used with the keywords virtual, override in C#.

Example of dynamic polymorphism in C#:

class Animal {
    public virtual void Speak() {
        Console.WriteLine("Animal sound");
    }
}

class Dog : Animal {
    public override void Speak() {
        Console.WriteLine("Bark");
    }
}

Animal myDog = new Dog();
myDog.Speak(); // Outputs "Bark"

Thus, polymorphism allows writing flexible and extensible code, where objects can behave differently despite having a common interface.

Can you explain the different types of polymorphism… - sobes.tech