Polymorphism in Java

Polymorphism in Java

In this article, I am going to discuss Polymorphism in Java. It is one of the primary pillars of object-oriented programming concept. Please read our previous where we discussed Wrapper Classes in Java. At the end of this article, you will understand the following pointers in detail as well as in the end we will discuss some frequently asked interview questions related to Polymorphism, Method Overloading, and Method Overriding in Java.

  1. What is Polymorphism?
  2. Why we need Polymorphism?
  3. Types of Polymorphism in Java?
  4. What is Compile-Time Polymorphism?
  5. What is Runtime Polymorphism?
  6. Understanding Method Overloading and Overriding in Java.
What is Polymorphism in Java?

Polymorphism is a Greek word where poly means many or several and morph means faces/ behaviors or functionalities. So, in simple words, we can say that polymorphism is the ability of an entity to take several forms. In order to understand polymorphism better, please have a look at the following image:

What is Polymorphism in Java?

As you can see in the above image, the vehicle is something that has several forms like a two-wheeler, three-wheeler, and four-wheeler, and so on. So this is one example of polymorphism.

According to the software standard, Polymorphism means one function with multiple functionalities or representations. In object-oriented programming, it refers to the ability of an object (or a reference to an object) to take different forms of objects. It allows a common data-gathering message to be sent to each class. Any Java object that can pass more than one IS-A test is considered to be polymorphic.

Polymorphism allows us to create consistent code. Polymorphism encourages called as ‘extendibility’ which means an object or a class can have it’s uses extended. Polymorphism makes software applications as a third party independent application.

Technically we can say that when a function shows different behaviors when we passed different types and number values, then it is called polymorphism. So behaving in different ways depending on the input received is known as polymorphism i.e. whenever the input changes, automatically the output or the behavior also changes.

Benefits of third-party independent application are as follows:
  • In future enhancements migrating from one-third party to another third party is the easiest task.
  • It reduces the development time of the application.
  • It decreases maintenance support.
  • It makes the application more dynamic.
Types of Polymorphism in Java:

Polymorphism is of two types in Java:

  1. Static polymorphism / compile-time polymorphism / Early binding
  2. Dynamic polymorphism / Run-time polymorphism / Late binding

The following images show the different types of polymorphisms in Java with their examples.

Types of Polymorphism in Java

What is Compile-Time Polymorphism?

It is also known as Static Polymorphism or Early Polymorphism. A polymorphism that is resolved during compile time is known as compile-time polymorphism. The compile-time Polymorphism feature is implemented with static binding. In Java, compile-time polymorphism is achieved through method overloading.

In the case of compile-time or static polymorphism, the object of the class recognizes which method to be executed for a given method call at the time of compilation and binds that method call with method definition.

In Java, this is happening in case of method overloading because in case of overloading each method will have a different signature and based on the method call we can easily recognize the method which matches the method signature.

Method Overloading in Java:

Defining a method multiple times with the same name in a single class with different parameter types then we can say that method is overloading. There are two ways to overload the method in java

  1. By changing the number of arguments
  2. By changing the data type

Example of Method Overloading:

package Demo;

public class Overloading {

 public static void main(String[] args) {
  System.out.println(10);
  System.out.println(true);
  //System.out.println(10, true); //error
  System.out.println(); //leaves blank line
  System.out.println(10.89);
 }

}

Output :

Method Overloading in Java

What is Runtime Polymorphism?

It is also known as Dynamic Polymorphism or Late Polymorphism. A polymorphism that is resolved during run time is known as dynamic polymorphism. The Dynamic Polymorphism feature is implemented with dynamic binding. In Java, dynamic polymorphism is achieved through method overriding.

In the case of Runtime Polymorphism for a given method call, we can recognize which method has to be executed exactly at runtime but not in compilation time because in case of overriding we have multiple methods with the same signature.

So, which method to be given preference and executed that is identified at Runtime and binds the method call with its suitable method. It is also called as dynamic polymorphism or late binding. Dynamic Polymorphism is achieved by using method overriding.

Method Overriding in Java:

Method Overriding is redefining the method from superclass into the subclass by adding new functionality or code. In Java, using the overriding concept superclass provides the freedom to the subclass for writing their own code instead of binding on superclass behavior or code.

Usage of Method Overriding :

Method overriding is used to provide the specific implementation of a method that is already provided by its superclass. Method overriding is used for runtime polymorphism.

Rules for Method Overriding:
  • The method name must be the same.
  • Method parameter types must be the same.
  • The method return type must be the same.
Sample Program for Method Overriding in Java:
package Demo;

class connection {
 void connect() {}
}

class oracleconnection extends connection
{
 void connect()	
 {
  System.out.println("connected to oracle.");	
 }
}

class mysqlconnection extends connection
{
 void connect() {
  System.out.println("connected to Mysql.");
 }
}

class Overriding{
 public static void main(String args[]) {
  oracleconnection a1 = new oracleconnection();
  mysqlconnection b1 = new mysqlconnection();
  
  a1.connect();
  b1.connect();
 }
}

Output:

Method Overriding in Java

Advantages of Polymorphism:
  • More flexible and reusable code.
  • The single variable name can be used to store variables of multiple data types.
  • More faster and efficient code at Runtime.
  • Code that is protected from extension by other classes.
  • More dynamic code at runtime.
Static and Dynamic Binding:

If you have more than one method of the same name or two variables of the same name in the same class hierarchy it gets tricky to find out which one is used during runtime as a result of there reference in code. This problem is resolved using static and dynamic binding in Java.

Binding is a mechanism to link between a method call and method actual implementation. Its process is used to a link which method or variable to be called as a result of there reference in code.

Static Binding in Java:

When the type of the object is determined at the compiled time (by the compiler), it is known as static binding. Binding of all the static, private, and final methods is done at compile-time.

Why binding of static, final, and private methods is always a static binding? 

Because the compiler knows that all such methods cannot be overridden and will always be accessed by the object of a local class. Hence compiler doesn’t have any difficulty determining the local object of the class. Static binding is better performance-wise (no extra overhead is required).

Example of Static Binding in Java:
package Demo;

public class StaticBinding {
   public static class superclass { 
         static void print() 
         { //print in superclass
             System.out.println("Hi!"); 
         } 
     } 
     public static class subclass extends superclass { 
         static void print() 
         { //print in subclass
             System.out.println("Hello!"); 
         } 
     } 
   
     public static void main(String[] args) 
     { 
         superclass A = new superclass(); 
         superclass B = new subclass(); 
         A.print(); 
         B.print(); 
     } 
}

Output :

Static Binding in Java

Dynamic Binding in Java:

When the type of the object is determined at run time, it is known as dynamic binding. In Dynamic binding compiler doesn’t decide the method to be called. Overriding is a perfect example of dynamic binding. In overriding both parent and child classes have the same method.

Example of Dynamic Binding in Java:
package Demo;

public class DynamicBinding {
 public static class superclass { 
        void print() 
        { //print in superclass
            System.out.println("Hi!"); 
        } 
    } 
  
    public static class subclass extends superclass { 
        @Override
        void print() 
        { //print in subclass
            System.out.println("Hello!"); 
        } 
    } 
  
    public static void main(String[] args) 
    { 
        superclass A = new superclass(); 
        superclass B = new subclass(); 
        A.print(); 
        B.print(); 
    } 
}

Output :

Dynamic Binding in Java

What is Method Overloading or Function Overloading in Java?

Method Overloading in Java is nothing but a process of creating multiple methods in a class with the same name but with a different signature. In Java, It is also possible to overload the methods in the derived classes as well. It means it allows us to create a method in the derived class with the same name as the method name defined in the base class.

In simple words, we can say that the Method Overloading in Java allows a class to have multiple methods with the same name but with a different signature.

When should we overload methods in Java?

If you want to execute the same logic but with different types of argument i.e. different types of values, then you need to overload the methods. For example, if you want to add two integers, two floats, and two strings, then you need to define three methods with the same name.

What are the advantages of using method overloading in Java? Or what are the disadvantages if we define methods with a different name?

If we overload the methods, then the user of our application gets comfort feeling in using the method with the impression that he/she calling one method by passing different types of values. The best example for us is the system defined “println()” method. It is an overloaded method, not a single method taking different types of values.

When is a method considered as an overloaded method in Java?

If two methods have the same name then those methods are considered as overloaded methods. Then the rule we need to check is both methods must have different parameter types/numbers/orders. But there is no rule on return type, non-accessibility modifier and accessibility modifier means overloading methods can have its own return type, non-accessibility modifier, and accessibility modifier because overloading methods are different methods.

Can we overload methods in the same class?

Yes, it is possible. No Compile Time Error, no Runtime Error. Methods can be overloaded in the same or in the super and subclasses because overloaded methods are different methods.

But we can’t override a method in the same class. It leads to Compile Time Error: “method is already defined” because overriding methods are the same methods with a different implementation.

What is Function Overriding in Java?

The process of re-implementing the superclass non-static method in the subclass with the same prototype (same signature defined in the superclass) is called Function Overriding or Method Overriding in Java. The implementation of the subclass overrides (i.e. replaces) the implementation of superclass methods.

The point that you need to keep in mind is the overriding method is always going to be executed from the current class object. Superclass method is called the overridden method and the sub-class method is called the overriding method.

When do we need to override a method in Java?

If the superclass method logic is not fulfilling the sub-class business requirements, then the subclass needs to override that method with required business logic. Usually, in most of the real-time applications, the superclass methods are implemented with generic logic which is common for all the next level sub-classes.

When is a sub-class method treated as an overriding method?

If a method in the sub-class contains the same signature as the superclass non-private non-static method, then the subclass method is treated as the overriding method and the superclass method is treated as the overridden method.

Difference Between Method Overloading and Method Overriding in Java

Method Overloading

Method Overriding

More than one method with the same name, different prototype in the same scope is known as Method Overloading. More than one method with the same name, the same prototype in different scope is known as Method Overriding.
Parameters must be different. Parameters must be the same.
It is also known as compile-time polymorphism. It is also known as run time polymorphism
It is performed within the class. It occurs in two classes.
The return type can be the same or different. The return type must be the same.
Static methods can be overloaded. Static methods cannot be overridden.
Static Binding is being used for overloaded methods. Dynamic binding is being used for overridden methods.
Difference Between Static Polymorphism and Dynamic Polymorphism:

Static Polymorphism

Dynamic Polymorphism

A type of polymorphism that collects the information to call a method during compile time. A type of polymorphism that collects the information to call a method during run time.
Occurs at Compile time. Occurs at Run time.
Known as Static Binding or Early Binding. Known as Dynamic Binding or Late Binding.
The execution speed is high. The execution speed is low.
Example: Method Overloading Example: Method Overriding
Difference Between Static Binding and Dynamic Binding:

Static Binding

Dynamic Binding

It is a binding that happened at compile time. It is a binding that happened at run time.
The actual object is not used for binding. An actual object is used for binding.
Private, static, and final methods show static binding because they cannot be overridden. Other than private, static, and final methods show static binding because they can be overridden.

In the next article, I am going to discuss Encapsulation in Java. Here, in this article, I try to explain Polymorphism in Java with examples. I hope you enjoy this article.

Leave a Reply

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