Define polymorphism and its types. How compile time polymorphism is different from run time polymorphism?


Q.) Define polymorphism and its types. How compile time polymorphism is different from run time polymorphism?

Subject: Object Oriented Programming and Methodology

Polymorphism:

Polymorphism is a fundamental concept in object-oriented programming (OOP) that allows objects of different classes to respond to the same method call in different ways. It enables the creation of a single interface that can be used to interact with multiple related objects. This increases the flexibility and reusability of the code.

Types of Polymorphism:

  1. Compile-Time Polymorphism:

Also known as static polymorphism, compile-time polymorphism occurs when a function or method call is resolved at compile time. This is achieved through function overloading and operator overloading.

  • Function Overloading: It allows multiple functions with the same name but different parameters to coexist in the same class. When a function is called, the compiler selects the appropriate function based on the number, type, and order of the arguments.

  • Operator Overloading: It allows operators to be applied to user-defined data types. When an operator is applied to an object, the compiler invokes the corresponding overloaded operator function defined for that object's class.

  1. Run-Time Polymorphism:

Also known as dynamic polymorphism, run-time polymorphism occurs when a method call is resolved at run time. This is achieved through method overriding.

  • Method Overriding: It allows subclasses to define their own implementations of methods inherited from their parent classes. When an object of a subclass calls an overridden method, the implementation defined in the subclass is executed, even if the method was originally defined in the parent class.

Differences between Compile-Time and Run-Time Polymorphism:

Feature Compile-Time Polymorphism Run-Time Polymorphism
Resolution Time Compile time Run time
Implementation Function overloading, operator overloading Method overriding
Inheritance Not required Required
Bound Classes Known at compile time Known at run time
Flexibility Less flexible More flexible
Performance Faster Slower

In summary, compile-time polymorphism resolves method calls at compile time, enabling the selection of the appropriate function or operator implementation based on the arguments. On the other hand, run-time polymorphism resolves method calls at run time, allowing subclasses to provide their own implementations of inherited methods, resulting in more flexible and dynamic behavior.