Functional Programming - Polymorphism


Advertisements


Polymorphism, in terms of programming, means reusing a single code multiple times. More specifically, it is the ability of a program to process objects differently depending on their data type or class.

Polymorphism is of two types −

  • Compile-time Polymorphism − This type of polymorphism can be achieved using method overloading.

  • Run-time Polymorphism − This type of polymorphism can be achieved using method overriding and virtual functions.

Advantages of Polymorphism

Polymorphism offers the following advantages −

  • It helps the programmer to reuse the codes, i.e., classes once written, tested and implemented can be reused as required. Saves a lot of time.

  • Single variable can be used to store multiple data types.

  • Easy to debug the codes.

Polymorphic Data Types

Polymorphic data-types can be implemented using generic pointers that store a byte address only, without the type of data stored at that memory address. For example,

function1(void *p, void *q) 

where p and q are generic pointers which can hold int, float (or any other) value as an argument.

Polymorphic Function in C++

The following program shows how to use polymorphic functions in C++, which is an object oriented programming language.

#include <iostream> 
Using namespace std: 

class A {  
   public: 
   void show() {    
      cout << "A class method is called/n"; 
   } 
}; 

class B:public A { 
   public: 
   void show() {   
      cout << "B class method is called/n"; 
   } 
};  

int main() {   
   A x;        // Base class object 
   B y;        // Derived class object 
   x.show();   // A class method is called 
   y.show();   // B class method is called 
   return 0; 
} 

It will produce the following output −

A class method is called 
B class method is called 

Polymorphic Function in Python

The following program shows how to use polymorphic functions in Python, which is a functional programming language.

Live Demo
class A(object): 
   def show(self): 
      print "A class method is called" 
  
class B(A): 
   def show(self): 
      print "B class method is called" 
  
def checkmethod(clasmethod): 
   clasmethod.show()  

AObj = A() 
BObj = B() 
  
checkmethod(AObj) 
checkmethod(BObj) 

It will produce the following output −

A class method is called 
B class method is called 


Advertisements