The Wayback Machine - https://web.archive.org/web/20240917145454/https://www.geeksforgeeks.org/difference-between-inheritance-and-polymorphism/
Open In App

Difference between Inheritance and Polymorphism

Last Updated : 18 Mar, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Inheritance is one in which a new class is created that inherits the properties of the already exist class. It supports the concept of code reusability and reduces the length of the code in object-oriented programming.

Types of Inheritance are:

  1. Single inheritance
  2. Multi-level inheritance
  3. Multiple inheritances
  4. Hybrid inheritance
  5. Hierarchical inheritance

Example of Inheritance: 

C++
#include <iostream>
using namespace std;

class A {
    int a, b;

public:
    void add(int x, int y)
    {
        a = x;
        b = y;
        cout << "addition of a+b is:" << (a + b) << endl;
    }
};

class B : public A {
public:
    void print(int x, int y)
    {
        add(x, y);
    }
};

int main()
{
    B b1;
    b1.print(5, 6);
    return 0;
}
Java
class A {
    int a, b;
    public void add(int x, int y)
    {
        a = x;
        b = y;
        System.out.println("addition of a + b is:" + (a + b));
    }
}
class B extends A {
    public void sum(int x, int y)
    {
        add(x, y);
    }

    // Driver Code
    public static void main(String[] args)
    {
        B b1 = new B();
        b1.sum(5, 6);
    }
}
C#
using System;

class A {
    private int a, b;

    // Method to perform addition and print the result
    public void Add(int x, int y)
    {
        a = x;
        b = y;
        Console.WriteLine("Addition of a + b is: "
                          + (a + b));
    }
}

class B : A {
    // Method to call the Add method from base class
    public void Print(int x, int y) { Add(x, y); }
}

class Program {
    static void Main(string[] args)
    {
        B b1 = new B();
        b1.Print(5, 6);
    }
}
JavaScript
// Define a class A
class A {
    constructor() {
        this.a = 0;
        this.b = 0;
    }

    // Method to calculate and print the sum of two numbers
    add(x, y) {
        this.a = x;
        this.b = y;
        console.log(`Addition of a + b is: ${this.a + this.b}`);
    }
}

// Define a class B that extends class A
class B extends A {
    // Method to call the 'add' method from the base class
    sum(x, y) {
        this.add(x, y);
    }
}

// Driver Code
const b1 = new B();

// Call the 'sum' method to calculate and print the sum of 5 and 6
b1.sum(5, 6);
Python3
class A:
    def __init__(self):
        self.a = 0
        self.b = 0

    def add(self, x, y):
        self.a = x
        self.b = y
        print("addition of a + b is:", self.a + self.b)


class B(A):
    def sum(self, x, y):
        self.add(x, y)


# Driver Code
b1 = B()

# custom sum 
b1.sum(5, 6)

Output
addition of a+b is:11



Here, class B is the derived class which inherit the property(add method) of the base class A.
Polymorphism: 
Polymorphism is that in which we can perform a task in multiple forms or ways. It is applied to the functions or methods. Polymorphism allows the object to decide which form of the function to implement at compile-time as well as run-time.

Types of Polymorphism are: 

  1. Compile-time polymorphism (Method overloading)
  2. Run-time polymorphism (Method Overriding)


Example of Polymorphism: 

C++
#include "iostream"
using namespace std;

class A {
    int a, b, c;

public:
    void add(int x, int y)
    {
        a = x;
        b = y;
        cout << "addition of a+b is:" << (a + b) << endl;
    }

    void add(int x, int y, int z)
    {
        a = x;
        b = y;
        c = z;
        cout << "addition of a+b+c is:" << (a + b + c) << endl;
    }

    virtual void print()
    {
        cout << "Class A's method is running" << endl;
    }
};

class B : public A {
public:
    void print()
    {
        cout << "Class B's method is running" << endl;
    }
};

int main()
{
    A a1;

    // method overloading (Compile-time polymorphism)
    a1.add(6, 5);

    // method overloading (Compile-time polymorphism)
    a1.add(1, 2, 3);

    B b1;

    // Method overriding (Run-time polymorphism)
    b1.print();
}
Java
class A {
    int a, b, c;

    public void add(int x, int y)
    {
        a = x;
        b = y;
        System.out.println("addition of a+b is:" + (a + b));
    }

    public void add(int x, int y, int z)
    {
        a = x;
        b = y;
        c = z;
        System.out.println("addition of a+b+c is:" + (a + b + c));
    }

    public void print()
    {
        System.out.println("Class A's method is running");
    }
};

class B extends A {
    public void print()
    {
        System.out.println("Class B's method is running");
    }

    // Driver Code
    public static void main(String[] args)
    {
        A a1 = new A();

        // method overloading (Compile-time polymorphism)
        a1.add(6, 5);

        // method overloading (Compile-time polymorphism)
        a1.add(1, 2, 3);

        B b1 = new B();

        // Method overriding (Run-time polymorphism)
        b1.print();
    }
}

Output
addition of a+b is:11
addition of a+b+c is:6
Class B's method is running


Difference between Inheritance and Polymorphism:

S.NOInheritancePolymorphism
1.Inheritance is one in which a new class is created (derived class) that inherits the features from the already existing class(Base class).Whereas polymorphism is that which can be defined in multiple forms.
2.It is basically applied to classes.Whereas it is basically applied to functions or methods.
3.Inheritance supports the concept of reusability and reduces code length in object-oriented programming.Polymorphism allows the object to decide which form of the function to implement at compile-time (overloading) as well as run-time (overriding).
4.Inheritance can be single, hybrid, multiple, hierarchical and multilevel inheritance.Whereas it can be compiled-time polymorphism (overload) as well as run-time polymorphism (overriding).
5.It is used in pattern designing.While it is also used in pattern designing.
6.

Example :

The class bike can be inherit from the class of two-wheel vehicles, which is turn could be a subclass of vehicles.  

Example : 

The class bike can have method name set_color(), which changes the bike’s color based on the name of color you have entered. 



Previous Article
Next Article

Similar Reads

Difference Between Compile Time And Run Time Polymorphism In C++
In this article, we will discuss the differences between the compile-time and runtime polymorphism in C++. What is Polymorphism? Poly means many and morph means forms or shape. Thus the word Polymorphism comes from Greek and it basically means having many forms. For example, Your DAD is your father. He's your mom's Husband. He's your grandma's son
4 min read
Difference between Compile-time and Run-time Polymorphism in Java
The word polymorphism means having many forms. In simple words, we can define polymorphism as the ability of a message to be displayed in more than one form. In this article, we will see the difference between two types of polymorphisms, compile time and run time. Compile Time Polymorphism: Whenever an object is bound with its functionality at the
3 min read
Virtual Functions and Runtime Polymorphism in C++
A virtual function is a member function that is declared in the base class using the keyword virtual and is re-defined (Overridden) in the derived class. It tells the compiler to perform late binding where the compiler matches the object with the right called function and executes it during the runtime. This technique falls under Runtime Polymorphi
8 min read
Difference between Single and Multiple Inheritance in C++
Single InheritanceSingle inheritance is one in which the derived class inherits the single base class either public, private, or protected access specifier. In single inheritance, the derived class uses the features or members of the single base class. These base class members can be accessed by a derived class or child class according to the acces
4 min read
Difference between Inheritance and Interface in Java
Java is one of the most popular and widely used programming languages. Java has been one of the most popular programming languages for many years. Java is Object Oriented. However, it is not considered as a pure object-oriented as it provides support for primitive data types (like int, char, etc). In this article, we will understand the difference
3 min read
Difference Between Priority Inversion and Priority Inheritance
Real-time operating systems also use scheduling methods where certain operations are given higher precedence over others so that they can be executed on time. But this type of prioritization leads to some problems, for instance Priority Inversion, which is the state in which a high-priority task is blocked by low-priority ones. From this article, w
7 min read
C++ Polymorphism
The word "polymorphism" means having many forms. In simple words, we can define polymorphism as the ability of a message to be displayed in more than one form. A real-life example of polymorphism is a person who at the same time can have different characteristics. A man at the same time is a father, a husband, and an employee. So the same person ex
7 min read
Inheritance and Friendship in C++
Inheritance in C++: This is an OOPS concept. It allows creating classes that are derived from other classes so that they automatically include some of the functionality of its base class and some functionality of its own. (See this article for reference) Friendship in C++: Usually, private and protected members of a class cannot be accessed from ou
2 min read
Constructor in Multilevel Inheritance in C++
Constructor is a class member function with the same name as the class. The main job of the constructor is to allocate memory for class objects. Constructor is automatically called when the object is created. Multilevel Inheritance Derivation of a class from another derived class is called Multilevel Inheritance. Class A is the base class for the d
2 min read
Constructor in Multiple Inheritance in C++
Constructor is a class member function with the same name as the class. The main job of the constructor is to allocate memory for class objects. Constructor is automatically called when the object is created. Multiple Inheritance: Multiple Inheritance is a feature of C++ where a class can derive from several(two or more) base classes. The construct
2 min read
Inheritance Ambiguity in C++
Pre-requisites: Inheritance in C++, Multiple Inheritance in C++ In multiple inheritances, when one class is derived from two or more base classes then there may be a possibility that the base classes have functions with the same name, and the derived class may not have functions with that name as those of its base classes. If the derived class obje
6 min read
C++ Multilevel Inheritance
Multilevel Inheritance in C++ is the process of deriving a class from another derived class. When one class inherits another class it is further inherited by another class. It is known as multi-level inheritance. For example, if we take Grandfather as a base class then Father is the derived class that has features of Grandfather and then Child is t
2 min read
C++ Hierarchical Inheritance
Inheritance is a feature of Object-Oriented-programming in which a derived class (child class) inherits the property (data member and member functions) of the Base class (parent class). For example, a child inherits the traits of their parents. In Hierarchical inheritance, more than one sub-class inherits the property of a single base class. There
4 min read
Hybrid Inheritance In C++
Before jumping into Hybrid Inheritance, let us first know what is inheritance. Inheritance is a fundamental OOP concept in C++ that allows a new class, also known as a subclass or derived class, to inherit properties and methods from an already-existing class, also known as a superclass or base class. C++ supports 5 types of inheritance: Single Inh
6 min read
Multiple Inheritance in C++
Multiple Inheritance is a feature of C++ where a class can inherit from more than one classes. The constructors of inherited classes are called in the same order in which they are inherited. For example, in the following program, B's constructor is called before A's constructor. A class can be derived from more than one base class. Eg: (i) A CHILD
5 min read
C++ Inheritance Access
Prerequisites: Class-Object in C++Inheritance in C++Before learning about Inheritance Access we need to know about access specifiers. There are three Access specifiers in C++. These are: public - members are accessible from outside the class, and members can be accessed from anywhere.private - members cannot be accessed (or viewed) from outside the
4 min read
Inheritance in C++
The capability of a class to derive properties and characteristics from another class is called Inheritance. Inheritance is one of the most important features of Object Oriented Programming in C++. In this article, we will learn about inheritance in C++, its modes and types along with the information about how it affects different properties of the
15+ min read
Does overloading work with Inheritance?
If we have a function in base class and another function with the same name in derived class, can the base class function be called from derived class object? This is an interesting question and as an experiment, predict the output of the following C++ program: [GFGTABS] C++ #include &lt;iostream&gt; using namespace std; class Base { public: int f(
5 min read
Difference between Difference Engine and Analytical Engine
Introduction: The development of computing technology has a rich history, with many inventions and innovations leading to the creation of the modern computer. Two such machines, the Difference Engine and Analytical Engine, were created by the English mathematician and inventor Charles Babbage in the 19th century. While these machines share some sim
7 min read
Difference between Voltage Drop and Potential Difference
Voltage Drop is defined as the decrease in the electric potential along the path of current that is flowing in an electric circuit. Voltage drop can be assigned at each point in the electric circuit that is proportional to the electrical elevation. The amount of energy delivered per second to any component in the circuit is equal to the voltage dro
4 min read
Difference Between Electric Potential and Potential Difference
The flow of electric charges is known as electricity, and it is responsible for producing electric current. An important word associated with electricity is electric potential. A potential difference is required to create the flow of electrons and hence, produce electricity. Before understanding the difference between electric potential and potenti
7 min read
Difference and Similarities between PHP and C
PHP is a server-side scripting language designed specifically for web development. It can be easily embedded in HTML files and HTML codes can also be written in a PHP file. The thing that differentiates PHP from a client-side language like HTML is, PHP codes are executed on the server whereas HTML codes are directly rendered on the browser. C is a
3 min read
Similarities and Difference between Java and C++
Nowadays Java and C++ programming languages are vastly used in competitive coding. Due to some awesome features, these two programming languages are widely used in industries as well as comepetitive programming . C++ is a widely popular language among coders for its efficiency, high speed, and dynamic memory utilization. Java is widely used in the
6 min read
Difference between Time Tracking and Time and Attendance Software
Time tracking and time and attendance software are tools that help businesses track the time that employees spend on tasks and their attendance records. These tools can help businesses automate their time tracking processes, reduce errors and inaccuracies, and ensure that employees are paid accurately for the time they work. Time tracking software
4 min read
Difference Between Single and Double Quotes in Shell Script and Linux
Single quotes and double quotes are both functional in Linux while working with shell scripts or executing commands directly in the terminal but there is a difference between the way the bash shell interprets them. Single quotes: Enclosing characters in single quotation marks (') holds onto the literal value of each character within the quotes. In
3 min read
Difference Between Monophyletic and vs Paraphyletic and vs Polyphyletic
In phylogeny, a taxon is a collection of organisms. Defining taxa makes it simpler to classify and identify creatures while also helping us to understand how they relate to one another. Based on these traits, taxa are developed. While some taxa are made up of unrelated creatures, others contain related species. Taxa classify descendants and ancesto
7 min read
Difference Between Grin And Smile And Smirk
Difference Between Grin And Smile And Smirk: Emotions are expressed by facial expressions. Facial expressions are considered an as important aspect of non-verbal communication. Facial expressions consist of various different body moments such as moving lips upward or downward, movement of raising the eyebrows, and giving the wide smile while descri
6 min read
Difference Between Store‑and‑Forward Switching and Cut‑Through Switching
Switching is a technique to transmit data between networks using switches that connect multiple LANs. Switches forward data packets based on MAC addresses, efficiently using bandwidth and reducing collisions. The three main types are: Circuit Switching: Dedicated path for the entire connection, used in traditional telephony.Message Switching: Entir
5 min read
Difference between Stop and Wait protocol and Sliding Window protocol
Both the Stop and Wait protocol and the Sliding Window protocol are the techniques to the solution of flow control handling. The main difference between the Stop-and-wait protocol and the Sliding window protocol is that in the Stop-and-Wait Protocol, the sender sends one frame and waits for acknowledgment from the receiver whereas in the sliding wi
5 min read
Difference between Black Box and White and Grey Box Testing
1. Black Box Testing : Black box testing is a type of software testing in which the functionality of the software is not known. The testing is done without the internal knowledge of the products. It is also called Functional testing. Black-box testing focuses on software’s external attributes and behavior. This type of testing looks at an applicati
4 min read
Practice Tags :