Polymorphism
Polymorphism is a fundamental concept in object-oriented programming (OOP) that allows objects of different classes to be treated as objects of a common superclass. It enables a single interface to represent different types of objects and allows methods to have different implementations based on the object's actual class. Polymorphism promotes code reusability, flexibility, and maintainability.
There are two types of polymorphism in OOP: compile-time polymorphism and runtime polymorphism
Compile-time polymorphism
Also known as static polymorphism or method overloading, this type of polymorphism occurs when multiple methods with the same name but different parameters (number, types, or order) are defined within the same class. The appropriate method is determined at compile-time based on the arguments passed to the method.
Example:
In this example, there are two Add methods with different parameter types. The correct method will be called based on the argument types.
Runtime polymorphism
Also known as dynamic polymorphism or method overriding, this type of polymorphism occurs when a subclass provides its own implementation of a method that is already defined in its superclass. The decision of which method to call is made at runtime based on the actual type of the object.
Example:
In this example, both Dog and Cat classes inherit from the Animal class and provide their own implementation of the Speak method. If you have a reference to an Animal object, you can call the Speak method without knowing the object's actual type:
In this case, the appropriate Speak method is called based on the actual type of the object at runtime.