Sobes.tech
Junior

What is polymorphism?

sobes.tech AI

Answer from AI

Polymorphism is a principle of object-oriented programming that allows objects of different classes to respond to the same message (method call) differently, depending on their actual type.

Types of polymorphism:

  • Ad-hoc (specialized) polymorphism:
    • Overloading: Methods with the same name but different signatures (number or types of parameters) within the same class.
    • Type coercion: Implicit or explicit conversion of data types.
  • Parametric polymorphism: Using generic types that allow writing code that works with different data types without losing type safety.
  • Subtype polymorphism: The ability to use a subclass object where a superclass object is expected.

Example of subtype polymorphism in Swift:

// Base class
class Vehicle {
    func startEngine() {
        print("Engine started.")
    }
}

// Subclass 1
class Car: Vehicle {
    override func startEngine() {
        print("Vroom-vroom!")
    }
}

// Subclass 2
class Motorcycle: Vehicle {
    override func startEngine() {
        print("Vrrrroooom!")
    }
}

// Using polymorphism
let vehicles: [Vehicle] = [Car(), Motorcycle(), Vehicle()]

for vehicle in vehicles {
    vehicle.startEngine() // Calls different implementations of startEngine() depending on the object type
}

Advantages of polymorphism:

  • Increases code flexibility and extensibility.
  • Simplifies making changes and adding new functionality.
  • Promotes code reuse.
  • Makes code more readable and maintainable.
What is polymorphism? — iOS - sobes.tech