Difference between Polymorphism and Inheritance in Java and OOP [Answer]

Programmers often confused among different object-oriented concepts e.g. between Composition and Inheritance, between abstraction and encapsulation, and sometimes between Polymorphism and Inheritance. In this article, we will explore the third one, Polymorphism vs Inheritance. Like in the real world, Inheritance is used to define the relationship between two classes. It's similar to the Father-Son relationship. In object-oriented programming, we have a Parent class (also known as the superclass) and a Child class (also known as the subclass). Similar to the real world, a Child inherits Parents' qualities, like its attributes, methods, and code. 

Inheritance is actually meant for code reuse. A child can reuse all the codes written in Parent class, and only write code for behavior that is different than the parent. Though it’s possible to restrict something to parent itself by using the private and final keyword in Java. On the other hand, Polymorphism is the ability of an object to behave in multiple forms.

For example, a Parent variable can hold a reference of either a Parent object or a Child object, so when you call a virtual method on Parent's object, it may go to the child's method depending upon which kind of object it is pointing at runtime. This is known as Polymorphism, and one of the most popular forms of Polymorphism is method overriding in Java.

By the way, If you look closely they are actually related to each other, because its Inheritance which makes Polymorphism possible, without any relationship between two class, it's not possible to write polymorphic code, which can take advantage of runtime binding of different objects.

You cannot use Polymorphism on something which is not inherited by the Child class like the private method can't be overridden in Java. Let's take an example to understand the difference between Polymorphism and Inheritance in Java more closely.




Code of Polymorphism vs Inheritance in Java?

The below code is a good example of How Inheritance and Polymorphism works. In Java, polymorphism is type-based, in order to write polymorphic code, you need to create a Type hierarchy, which is achieved using Inheritance. In this example, we have an abstract class to represent a Connection and we have two sub-classes TCP and UDP

All three are related to each other via Inheritance, Connection is Parent while TCP and UDP are Child classes. Now any code, which is based upon Connection will be polymorphic and can behave differently based upon whether the actual connection is of type TCP or UDP

This Polymorphism magic is constructed by method overriding in Java, but it's the principle of programming for interfaces than implementation, which motivates to write polymorphic code. Why you should write Polymorphic code? Simple to be flexible, to accommodate change, and to take advantage of evolution at the later stage of development. 

A static code is fixed when written, but a Polymorphic code can evolve.

public class Test {
        public static void main(String args[]) {
                Connection connection = new TCP();
                connection.connect();
        }
}

/**
   * Base class to represent a Connection.
   */
public abstract class Connection{
        protected String data;
       
        public void connect(){
                System.out.println("Connecting ....")
        }
       
        public void inputDate(String data){
                this.data = data;
        }
}

public class TCP extends Connection {
       
        @Override
        public void connect() {
                System.out.println("Connection reliably but slow ..");
        }
}

public class UDP extends Connection {
       
        @Override
        public void connect(){
                System.out.println("Connecting fast but no guarantee of data delivery");
        }
}

Output:
Connection reliably but slow ..


In short here are the key difference between Polymorphism and Inheritance in Java :

1) Inheritance defines the father-son relationship between two classes, While Polymorphism takes advantage of that relationship to add dynamic behavior in your code.

2) Inheritance is meant for code reuse, the initial idea is to reuse what is written inside the Parent class and only write code for new functions or behavior in the Child class. On the other hand, Polymorphism allows Child to redefine already defined behavior inside the parent class. Without Polymorphism, it's not possible for a Child to execute its own behavior while represented by a Parent reference variable, but with Polymorphism he can do that.

3) Polymorphism helps tremendously during Maintenance. In fact, many object-oriented design principles are based on Polymorphism like programming for interface than implementation, which advocates to use interface everywhere in your code, to represent variable, in method parameters, in the return type of method, etc; so that code can take advantage of polymorphism and do more than what was expected it to do during writing.

4) Java doesn't allow multiple inheritances of classes but allows multiple inheritances of Interface, which is actually required to implement Polymorphism. For example, a Class can be Runnable, Comparator, and Serializable at the same time, because all three are interfaces. This makes them to pass around in code e.g. you can pass instances of this class to a method that accepts Serializable, or to Collections.sort() which accepts a Comparator.

5) Both Polymorphism and Inheritance allow Object-oriented programs to evolve. For example, by using Inheritance you can define new user types in an Authentication System and by using Polymorphism you can take advantage of already written authentication code. Since, Inheritance guarantees minimum base class behavior, a method depending upon superclass or super interface can still accept an object of the base class and can authenticate it.

6) In the UML diagram, Inheritance is represented using arrows, pointing towards the Parent class. For example in this diagram, AbstractPerson is Parent class for Employee, Manager, and CustomerContact class.

Inheritance vs Polymorphism in Java



That's all about the difference between Inheritance and Polymorphism in Java. Though they are different things but not orthogonally, in fact, they work together to give Object-oriented programming its true power. Because of Inheritance and Polymorphism, your object-oriented code can do a lot more than what is expected from it initially. It allows your software to grow, evolve and meet the needs of the future, an important characteristic of any software.

Other Java programming and OOP tutorials You may like

Thanks for reading this article so far. If you like an object-oriented programming tutorial then please share it with your friends and colleagues. If you have any questions or feedback then please drop a note.

3 comments:

  1. Use simple language for first attempt learners to understand

    ReplyDelete
  2. there is no one abstract method in connection class so why you make that class Abstract..?

    ReplyDelete

Feel free to comment, ask questions if you have any doubt.