Sobes.tech
Junior — Middle

Can you give an example illustrating different types of polymorphism in object-oriented programming?

sobes.tech AI

Answer from AI

In object-oriented programming, polymorphism allows objects of different classes to handle method calls with the same name differently.

1. Compile-time polymorphism (static polymorphism):

  • Method overloading — multiple methods with the same name but different parameters.
class Calculator {
    func add(a: Int, b: Int) -> Int {
        return a + b
    }
    func add(a: Double, b: Double) -> Double {
        return a + b
    }
}

2. Runtime polymorphism (dynamic polymorphism):

  • Method overriding in subclasses.
class Animal {
    func sound() {
        print("Some sound")
    }
}

class Dog: Animal {
    override func sound() {
        print("Bark")
    }
}

class Cat: Animal {
    override func sound() {
        print("Meow")
    }
}

let animals: [Animal] = [Dog(), Cat()]
for animal in animals {
    animal.sound()  // Will output "Bark" and "Meow"
}

Thus, polymorphism allows using a single interface to work with different types of objects.

Can you give an example illustrating different types… - sobes.tech