DEV Community

Jai Desai
Jai Desai

Posted on

Understanding Inheritance and Polymorphism: Simplified OOP Concepts

Inheritance

Inheritance means creating a new class based on an existing class. The new class inherits attributes and methods from the existing class.

Example Explanation

Imagine you have a general class called Animal. You can create a specific class called Dog that inherits everything from Animal and adds its own features.

code

Image description
//continue the example
Image description

Explanation of the Example

  • Animal class (Parent class):

    1. Has an attribute 'name'.
    2. Has a method 'eat'.
  • Dog class (Child class):

    1. Inherits everything from 'Animal'.
    2. Adds its own method 'bark()'.
  • my_dog Object:

    1. Can use the 'eat()' method from 'Animal'.
    2. Can use the 'bark()' method from 'Dog'.

Polymorphism

Polymorphism means "many shapes". It allows methods to do different things based on the object it is acting upon, even if they share the same name.

Example Explanation

Let's continue with the 'Animal' and 'Dog' classes, and add another class called 'Cat'.

Code

Image description
// continue the example
Image description

Explanation of the Example

  • Animal Class:

    1. Has a method 'make_sound()' that prints a generic message.
  • Dog Class:

    1. Inherits from 'Animal'.
    2. Overrides 'make_sound()' to print a dog-specific message.
  • Cat Class:

    1. Inherits from 'Animal'.
    2. Overrides 'make_sound()' to print a cat-specific message.
  • my_dog and my_cat Objects:

    1. Both use the make_sound() method, but each prints a different message based on their class.

Summary

  1. Inheritance: Allows a class to inherit attributes and methods from another class.
  2. Polymorphism: Allows methods to do different things based on the object they are called on, even if they share the same name.

In next article we will Explore Abstraction & Encapsulation and please give me your feedback

Top comments (0)