Difference Between Inheritance and Polymorphism

Computer ProgrammingProgrammingMiscellaneous

In this post, we will understand the difference between inheritance and polymorphism −

Inheritance

  • It is a part of object oriented programming paradigm.

  • It can be implemented in C++, Java, Python, and other object oriented programming languages.

  • It is the method in which a new class is created that can take and use the properties of an already existing class.

  • The already existing class is known as ‘parent/base class’ and the class that uses this class is known as ‘child/derived class’.

  • It helps reuse the code.

  • It reduces the size of the code while implementing object oriented programming.

  • Types of inheritance −

    • Single inheritance

    • Multi-level inheritance

    • Multiple inheritance

    • Hybrid inheritance

    • Hierarchical inheritance

  • It can be used in pattern design.

Example

class base_class:
   def __init__(self, f_name, l_name):
      self.firstname = f_name
      self.lastname = l_name
   def print_it(self):
      print(self.firstname, self.lastname)
   print("An instance of 'base_class' is created")
   my_instance = base_class("John", "Will")
   print("A method 'print_it' is being called using the created instance")
   my_instance.print_it()

Output

An instance of 'base_class' is created
A method 'print_it' is being called using the created instance
John Will

Polymorphism

  • ‘Poly’ means multiple and ‘morph’ means forms.

  • It is a part of object oriented programming paradigm.

  • It can be implemented in C++, Java, Python, and other object oriented programming languages.

  • Hence, polymorphism refers to the method of performing a specific task in multiple ways.

  • This can be used while using functions.

  • It allows the object of the class to decide which form it has to take to work with methods and attributes of the class.

  • Types of polymorphism −

    • Compile-time polymorphism- It is also known as method overloading.

    • Run-time polymorphism- It is also known as method overriding.

  • It can be used in pattern design.

Example

def add_vals(val_1, val_2, val_3 = 1):
   my_result = val_1 + val_2 + val_3
   return my_result

print("The method is being called by passing two parameters")
print(add_vals(7, 9))
print("The method is being called by passing three parameters")
print(add_vals(11, 23, 45))

Output

The method is being called by passing two parameters
17
The method is being called by passing three parameters
79
raja
Published on 24-Mar-2021 13:40:48
Advertisements