Codele / Advanced programming
Polymorphism
Give the same instruction to different objects and each one does it in its own way. The code that gives the instruction does not need to know which kind of object it is talking to.
- Polymorphism means “many forms”: one instruction, and each object answers in the way its own class defines.
- It works because a child class can override a method: replace the parent’s version with its own.
- The code that calls animal.speak() only needs an object that can speak. The object itself decides which speak runs. Python and JavaScript do not check this beforehand.
- Adding a new kind of animal does not change the loop. A long if/else on the type would need an edit every time.
- C++ needs the word virtual on the parent’s method, or the parent’s version runs. Go has no inheritance: any type with a Speak method fits the Animal interface.
Loading the playable lesson…