Wednesday, April 26, 2023

Difference between Inheritance and Polymorphism in Java and OOP - Example

Both Inheritance and Polymorphism are key OOP concepts and similar to Abstraction and Encapsulation, they are also closely related to each other. Because of their similarities, many OOP programmers, especially beginners get confused between Inheritance and Polymorphism. Even though they are closely related and you need Inheritance to support runtime Polymorphism they are a totally different concept. Inheritance refers to the ability of classes or objects to inherit properties of other classes or interfaces. It means you can write code for common functionalities and reuse it at different places by just using Inheritance and not re-writing those codes again and again. For example, you can write code to

Inheritance vs Polymorphism in Java and Object-Oriented Programming

Let's revisit some key differences between Inheritance and Polymorphism in object-oriented programming

1. Class vs Object 

Inheritance is used to define a class or interface hierarchy. You extract common functionality on superclass and allow derived classes to get more specific by adding specific functionality.

On the other hand, Polymorphism allows you to do the same operation differently depending upon which context and which object is doing the operation.



2. Code Reuse 

One of the key advantages of Inheritance is code reuse. You don't need to write the same code again and again if it is needed by multiple classes. You can extract the common functionality on the base class and let other classes simply use inheritance to get that functionality. In another word, it reduces the amount of duplicate code and promotes the DRY practice.

For example, if you are designing a class hierarchy for the Finance and Insurance industry, you can create a base class called Insurance, which should have basic properties like covered, the sum assured, premium, etc.

Now, if your application needs to support automobile insurance like the CarInsurance, it just needs to extend the Insurance base class to add specific details required by car insurance companies like the registration number of the car, brand, etc.

Similarly, Health Insurance applications can reuse the same base class for calculating premiums, keeping a record of sum assured, and other basic details. They can further enrich the derived class by adding more specific details required by health insurance companies like pre-existing diseases, co-payment details, etc.

In short, we have reused all the code which is common among all types of insurance like premium and sum assured. Also, many SOLID Principles of Object-Oriented Design like the Open Close Design Principle are based on Inheritance and Polymorphism, which help you to write better code.

Inheritance vs Polymorphism in Java


Polymorphism can also come in handy here to write code for calculating premiums. Assuming, the premium is calculated differently for different types of insurance then you can override the calculatePremium() method in derived or subclasses to represent different types of premium calculation.

The benefit of using Polymorphism here is that all the common functionality like report generations, sending premium receipts, or premium reminders can still use the same calculatePreimum() method for performing their duty. They don't need to worry about the fact that different types of insurance are calculating premiums using different formulas.


3. Flexibility 

If Inheritance provides "code re-usability" then Polymorphism provides the "flexibility" to your code. As I mentioned in my previous example, you can add a new kind of Insurance without re-writing code to generate receipts, premium reminders, and other kinds of reports.

By using Polymorphism, you can encapsulate the code which is different inside the same method declared by the superclass. The Clean Code by Uncle Bob has a good write-up and example on this.

best book to improve coding



4. Right Usage 

One of the best practices in the OOP world is using Inheritance for defining type hierarchies using the interface. This is also advised in Effective Java 3rd Edition by Joshua Bloch. By defining types, you create a path for Polymorphism.


5. extends vs implements 

Inheritance in Java is implemented using the "extends" and "implements" keywords. A class can extend another class or implement one or more interfaces. When it does that, the parent-child relationship is established between two classes or interfaces.

For example, in the following code, the MyClass is now a child or both Canvas and Runnable:

public class MyClass extends Canvas implements Runnable{

@Overide
public void paint(Graphics g){
   ... some code
  }

@Override
public void run(){
  ... some code
  }

}

This means you a reference variable of Runnable or Canvas can point to an object of MyClass and if you call paint() or run() method then these methods will be called instead of paint() method defined in Canvas and run() method defined in Runnable. This is the power of Polymorphism which comes from Inheritance.

If you are interested in code quality,  you can further see Clean Code: Writing Code for Humans By Cory House to learn more about writing better code in the real world.

best course to learn Coding and Object Oriented Programming



Inheritance vs Polymorphism - Summary

Let's revisit some of the key differences between Inheritance and Polymorphism in object-oriented programming

1. Inheritance creates a parent-child relationship between two objects, while, Polymorphism takes advantage of that relationship to execute different codes for the same operation depending upon which object is performing it.

2. Inheritance provides code reusability, while Polymorphism provides flexibility and dynamic behavior.

3. Use Inheritance to define type hierarchy, Use Polymorphism to write generic code like code which depends upon interface than implementation.

4. Inheritance is supported using extended and implemented keywords in Java, Polymorphism is supported using Overloading and Overriding Concepts.

5. There are two types of Inheritance, single Inheritance, and multiple Inheritance, Java doesn't support Multiple Inheritance. Similarly, there are two types of Polymorphism compile-time polymorphism and runtime polymorphism, Java support. You can further check The Complete Java Masterclass to learn more about Inheritance in Java.

Difference between Inheritance and Polymorphism in Java and Object Oriented Programming



That's all about the difference between Inheritance and Polymorphism in Java and Object Oriented Programming. As I said, Inheritance is about the ability to inherit common properties and then add specific properties depending upon need. It establishes the parent-child relationship which is key for Polymorphism.

It is a Greek term that means "one name many forms" and that's exactly what it does. It allows the same operation to behave differently depending on which object is calling it. For example, the sound() method of Animal class may produce "meow" or "woof" depending on whether we call it using Cat object or Dog instance.

You can use Inheritance for code-reuse, though Composition is another choice, and Polymorphism is key for writing flexible software.



Thanks for reading this tutorial. If you like this question and my explanation then please share it with your friends and colleagues. If you have any questions or feedback then please drop a note. 

No comments:

Post a Comment