Difference between Polymorphism and Inheritance in Java and OOP

Programmers often confused among different object oriented concepts e.g. between Composition and Inheritance, between abstraction and encapsulation and sometime between Polymorphism and Inheritance. In this article, we will explore third one, Polymorphism vs Inheritance. Like in real world, Inheritance is used to define the relationship between two classes. It's similar to Father-Son relationship. In object oriented programming, we have a Parent class (also known as the super class) and a Child class (also known as the subclass). Similar to the real world, Child inherits Parents qualities, e.g. it's attribute, 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 behaviour which 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 an ability of Object to behave in multiple form.

For example a Parent variable can hold 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 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 form 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 Child class e.g. private method can't be overridden in Java. Let's take an example to understand difference between Polymorphism and Inheritance in Java more closely.




Code of Polymorphism vs Inheritance in Java

Inheritance vs Polymorphism in Java
Below code is 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 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 actual connection is of type TCP or UDP. This Polymorphism magic is constructed by method overriding in Java, but its 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 on 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 key difference between Polymorphism and Inheritance in Java :

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

2) Inheritance is meant for code reuse, initial idea is to reuse what is written inside Parent class and only write code for new function or behaviour in Child class. On the other hand Polymorphism allows Child to redefine already defined behaviour inside parent class. Without Polymorphism it's not possible for a Child to execute its own behaviour 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 e.g. programming for interface then implementation, which advocates to use interface everywhere in your code, to represent variable, in method parameters, in 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 inheritance of classes, but allows multiple inheritance of Interface, which is actually require to implement Polymorphism. For example a Class can be Runnable, Comparator and Serializable at same time, because all three are interfaces. This makes them to pass around in code e.g. you can pass instance of this class to a method which 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 behaviour, a method depending upon super class or super interface can still accept object of base class and can authenticate it.

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


That's all about difference between Inheritance and Polymorphism in Java. Though they are different thing 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 needs of future, an important characteristic of any software.


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