Polymorphic example
1class Animal:
2def sound(self):
3return "Generic sound"
4class Dog(Animal):
5def sound(self):
6return "Woof!"
Polymorphism lets different objects respond to the same method call in their own way.
Call .speak() on a Dog or a Cat. Each class does its own version.
That is polymorphism: one interface, many behaviors.
Polymorphism means "many forms". The same method name can behave differently depending on which object calls it. A Dog's sound() says "Woof", but a Cat's sound() says "Meow".
classDiagram
class Animal {
+sound()
}
class Dog {
+sound()
}
class Cat {
+sound()
}
class Bird {
+sound()
}
Animal <|-- Dog
Animal <|-- Cat
Animal <|-- Bird
Animal : sound()
Dog : sound() "Woof!"
Cat : sound() "Meow!"
Bird : sound() "Chirp!"
Many animals have a sound() method. Dog.sound() = bark, Cat.sound() = meow, Bird.sound() = chirp. Different implementation, same interface. You can call sound() on any animal.