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 September 6, 2024 by Abhishek Sharma

In object-oriented programming (OOP), polymorphism and inheritance are fundamental concepts that enable code reusability, flexibility, and scalability. Both concepts play a crucial role in building efficient and organized codebases by allowing developers to create systems that are easy to maintain and extend. However, while they are related, polymorphism and inheritance serve distinct purposes. Understanding the differences between these two concepts is essential for mastering OOP principles and writing better code.

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
Polymorphism and inheritance are two pillars of object-oriented programming that work together to enhance flexibility, code reuse, and maintainability. While inheritance focuses on establishing a hierarchical relationship between classes, polymorphism emphasizes the ability of methods to work with objects of different types in a uniform manner. Understanding both concepts and their distinctions helps programmers develop robust and modular code that can handle a wide range of scenarios efficiently.

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.

Q1: What is polymorphism in object-oriented programming?
A1:
Polymorphism in OOP allows objects of different classes to be treated as objects of a common superclass. It enables methods to perform different tasks based on the object that calls them, facilitating flexibility in method invocation.

Q2: What is inheritance in object-oriented programming?
A2:
Inheritance is a mechanism where one class derives properties and methods from another class, allowing code reuse and the establishment of a hierarchical relationship between classes (parent-child).

Q3: How are polymorphism and inheritance related?
A3:
Polymorphism often relies on inheritance. Inheritance defines a relationship between classes, and polymorphism allows methods to work on objects of these related classes in a consistent way. However, they are distinct concepts, with polymorphism focusing on behavior and inheritance on the structure of classes.

Q4: Can polymorphism exist without inheritance?
A4:
Yes, polymorphism can exist without inheritance through interface-based polymorphism or method overloading. However, runtime polymorphism (method overriding) typically requires inheritance.

Q5: What is an example of polymorphism in practice?
A5:
An example of polymorphism is a method like move() that behaves differently for a Car, Plane, or Bicycle object, even though they all inherit from the same Vehicle class.

Q6: What is the main benefit of using inheritance?
A6:
The primary benefit of inheritance is code reuse. By defining common properties and behaviors in a parent class, subclasses can inherit and extend or modify those features without duplicating code.

Q7: How does polymorphism improve code flexibility?
A7:
Polymorphism improves code flexibility by allowing methods to process objects of different types in a uniform way. This means that the same method can be used for different objects, reducing the need for multiple method definitions.

Leave a Reply

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