Junior
Kas ir polimorfisms programmēšanā?
sobes.tech AI
Atbilde no AI
Polimorfisms ir spēja objektiem no dažādām klasēm reaģēt uz tiem pašiem ziņojumiem (metožu izsaukumiem) dažādos veidos.
Vienkārši sakot, tas pats metodes izsaukums var darboties atšķirīgi atkarībā no objekta, kas to izsauc. To panāk ar mantošanu un metožu pārrakstīšanu, kā arī ar saskarnēm.
Piemērs Swift valodā:
protocol Animal {
func makeSound()
}
class Dog: Animal {
func makeSound() {
print("Hau")
}
}
class Cat: Animal {
func makeSound() {
print("Miau")
}
}
func playSound(animal: Animal) {
animal.makeSound()
}
let dog = Dog()
let cat = Cat()
playSound(animal: dog) // Izdrukās: Hau
playSound(animal: cat) // Izdrukās: Miau
Šeit funkcija playSound pieņem Animal tipa objektu, bet atkarībā no konkrētās klases (Dog vai Cat) tiek izsaukta atbilstošā makeSound metodes realizācija.