Sobes.tech
Junior — Middle

Kas saaksid anda näite, mis illustreerib erinevaid polümorfismi liike objektorienteeritud programmeerimises?

sobes.tech AI

Vastus AI-lt

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

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 print "Bark" and "Meow"
}

Thus, polymorphism enables using a single interface to work with different object types.