Lec 10 POlymorphism
Lec 10 POlymorphism
Polymorphism
• Polymorphism means "many forms", and it occurs when we have
many classes that are related to each other by inheritance.
• Inheritance lets us inherit attributes and methods from another class.
• Polymorphism uses those methods to perform different tasks.
• This allows us to perform a single action in different ways.
For example, think of a base class called Animal that has a method
called animalSound().
• Derived classes of Animals could be Pigs, Cats, Dogs, Birds-
And they also have their own implementation of an animal sound (the
pig oinks, and the cat meows, etc.)
Polymorphism and it’s Types
Now we can create Pig and Dog objects and override the animalSound() method:
Benefits of Polymorphism
Code Reusability:
Polymorphism allows us to reuse code by invoking methods via a
common interface, which reduces code duplication and improves
modularity.
Flexibility:
By considering objects of multiple classes as instances of a superclass,
we may build generic code that works with various objects, enhancing
flexibility and adaptability.
Maintenance:
Polymorphism improves cleaner code by decoupling object behavior
from specific implementations. This reduces code maintenance and
improves readability.
Extensibility:
Polymorphism allows for creating new classes without altering existing
code. New subclasses can be easily incorporated into the system,
allowing for easy extension.