Sobes.tech
Junior — Middle

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

sobes.tech AI

Answer from AI

Polymorphism is an object-oriented programming principle that allows objects of different classes to respond to the same message (method) in different ways.

There are two main types of polymorphism:

  1. Compile-time (static) polymorphism — method and operator overloading.
  2. Runtime (dynamic) polymorphism — method overriding in subclasses.

Example of dynamic polymorphism in C#:

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

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

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

// Usage
Animal myDog = new Dog();
Animal myCat = new Cat();
myDog.Speak(); // Outputs "Bark"
myCat.Speak(); // Outputs "Meow"

Thus, the same method call Speak() behaves differently depending on the object type.

Can you explain the concept of polymorphism in… - sobes.tech