Sobes.tech
Junior — Middle

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

sobes.tech AI

Answer from AI

Object-oriented programming (OOP) polymorphism has several main types:

  1. Subtype polymorphism — the most common, implemented through inheritance and method overriding. It allows using subclass objects in place of superclass objects.

  2. Parametric polymorphism — implemented via generics, where functions or classes work with any data types.

  3. Ad-hoc polymorphism — includes function and operator overloading, where one function has multiple implementations with different parameter types.

  4. Runtime polymorphism — achieved through virtual methods and dynamic binding, where method calls are determined at runtime.

Example of subtype polymorphism in Swift (iOS):

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()  // Call depends on actual object type
}

This demonstrates subtype polymorphism, where the method invoked depends on the actual object type at runtime.

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