Get free ebooK with 50 must do coding Question for Product Based Companies solved
Fill the details & get ebook over email
Thank You!
We have sent the Ebook on 50 Must Do Coding Questions for Product Based Companies Solved over your email. All the best!

What is the Difference Between Polymorphism and Inheritance?

Last Updated on August 9, 2023 by Mayank Dham

In the vast landscape of object-oriented programming, two fundamental concepts, polymorphism, and inheritance, stand as pillars upon which modern software development relies. While both play pivotal roles in achieving code reusability and flexibility, they represent distinct paradigms that require comprehensive understanding. In this article, we embark on a journey to explore the intricacies of polymorphism and inheritance, unraveling their essence and shedding light on the crucial distinctions that set them apart.
So, let’s embark on this enlightening voyage to the difference between polymorphism and inheritance, uncovering the unique roles they play in shaping the foundation of object-oriented programming. Grab your coding compass, and let’s set sail!

What is Inheritance?

Inheritance, in the context of object-oriented programming (OOP), is a fundamental concept that allows a new class (called the derived class or subclass) to inherit properties and behaviors from an existing class (called the base class or superclass). This mechanism facilitates code reusability and promotes the creation of a hierarchical relationship between classes.

When a class inherits from another class, it gains access to all the public and protected members (attributes and methods) of the base class. This means that the derived class can use and extend the functionalities of the superclass without having to rewrite the entire code. Inheritance forms the "is-a" relationship between classes, where the derived class is a specialized version of the base class. The syntax typically looks like this:
// Java syntax
class Superclass {
// Superclass members
}

class Subclass extends Superclass {
    // Subclass members and additional functionalities
}

In this example, the Subclass is inheriting from the Superclass. Any methods or variables declared as public or protected in the Superclass will be accessible within the Subclass. Additionally, the Subclass can add its specific methods and properties or override existing methods from the Superclass to tailor the behavior as needed.

Types of Inheritance are:

  • Single inheritance
  • Multi-level inheritance
  • Multiple inheritances
  • Hybrid inheritance
  • Hierarchical inheritance

Example of Inheritance:

#include
using namespace std;

class A {
    int a, b;

public:
    void add(int x, int y)
    {
        a = x;
        b = y;
        cout << (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);
}
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);
    }
}
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 

Class B is the descended class in this instance and it inherits the property (add method) from base class A.

What is Polymorphism?

Polymorphism is another important concept in object-oriented programming (OOP) that allows objects of different classes to be treated as objects of a common superclass. It enables a single interface to represent different data types or classes, allowing code to work with different types of objects transparently. Polymorphism promotes flexibility, extensibility, and simplification of code.

There are two main types of polymorphism: compile-time (static) polymorphism and runtime (dynamic) polymorphism.

Compile-time (Static) Polymorphism:

This type of polymorphism is resolved during compile-time. It is achieved through method overloading and operator overloading. Method overloading allows a class to have multiple methods with the same name but different parameters, and the appropriate method is selected based on the arguments provided during the compilation phase. Operator overloading allows operators (e.g., +, -, *, /) to have different implementations for different data types or classes.

Example of method overloading in Java:
class MathOperations {
int add(int a, int b) {
return a + b;
}

    double add(double a, double b) {
        return a + b;
    }
}

Runtime (Dynamic) Polymorphism:

This type of polymorphism is resolved during runtime. It is achieved through method overriding. Method overriding allows a subclass to provide a specific implementation of a method that is already defined in its superclass. When the method is called on an object of the subclass, the overridden method in the subclass is executed.

Example of method overriding in Java:
class Animal {
void makeSound() {
System.out.println("Animal makes a generic sound.");
}
}

class Dog extends Animal {
    @Override
    void makeSound() {
        System.out.println("Dog barks.");
    }
}

Difference between Inheritance and Polymorphism:

Here is the tabular form difference between inheritance and polymorphism.

S.NO Inheritance Polymorphism
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.

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. |

Conclusion
In conclusion, polymorphism and inheritance are two fundamental concepts in object-oriented programming, but they serve different purposes and operate at different levels. While both are key components of OOP and facilitate code reuse and abstraction, they address distinct aspects of designing and structuring classes.

Polymorphism focuses on the ability of objects of different classes to be treated as objects of a common superclass, allowing for flexibility and dynamic method dispatch at runtime. It enables a single interface to represent various data types and supports method overloading and method overriding.

Inheritance, on the other hand, establishes a hierarchical relationship between classes, where a new class (subclass) inherits properties and behaviors from an existing class (superclass). It fosters code reusability and promotes the "is-a" relationship between classes.

FAQ on difference between polymorphism and inheritance:

Here are some FAQs on the difference between Polymorphism and inheritance.

1. Can a class have both inheritance and polymorphism?
Yes, it is common for a class to exhibit both inheritance and polymorphism. Inheritance allows the class to inherit properties and methods from a superclass, while polymorphism enables the class to override or overload methods and provide its own specific implementations.

2. Which one is more important, polymorphism or inheritance?
Both polymorphism and inheritance are essential concepts in OOP, and their significance depends on the specific requirements of the software design. Polymorphism allows for dynamic method dispatch and flexibility in handling different object types, while inheritance promotes code reusability and hierarchical relationships between classes.

3. What is the main benefit of using polymorphism?
The primary advantage of polymorphism is its ability to write code that can work with objects of different classes through a common interface, without needing to know the specific class at compile-time. This enhances code flexibility and promotes easier maintenance and extensibility.

4. When should I use inheritance, and when should I use polymorphism?
Use inheritance when you want to create a specialized class that inherits properties and behaviors from a more general class. It is suitable for representing "is-a" relationships. Use polymorphism when you want to design code to be generic and work seamlessly with multiple related classes through a common interface.

5. Can polymorphism exist without inheritance?
Yes, polymorphism can exist without inheritance. Polymorphism can be achieved through interfaces, abstract classes, or simply by using method overloading without any inheritance relationship between classes.

Leave a Reply

Your email address will not be published. Required fields are marked *