Polymorphism in Java

Polymorphism is one of the basic features of the Object Oriented Programming(OOP). It means many forms. It can be realized with both methods and operators. For example:

With integers, + operator performs arithmetic addition and with strings it concatenates them. So + operator has many forms i.e + is polymorphic.

Polymorphism can be realized at both compile time and run time. There are different mechanisms put in place to realize these two categories of polymorphism.


1. Compile-Time Polymorphism

  • It is achieved mainly through method overloading.
  • It is also called Early binding or Static binding because the method that would be run is known at the compile time.

In method overloading, we have got a bunch of methods with same name but different argument list. The argument list can vary in both number and data-type of the arguments. It can also vary in the order in which data types of parameters are declared.

Note that Java doesn’t support only return type based method overloading.


2. Run-Time Polymorphism

  • It is achieved mainly through method overriding.
  • It is also called Late binding or Dynamic binding because the method that would be run is  not known until the runtime.

Method overriding is used in context of inheritance. In the subclass, we define a method with the same name and type parameter as that in the superclass. The subclass may alter the internal details of the method in a way suited to its needs. The method in the subclass is called the overriding method and the method in the superclass is called the overridden method.

We use a superclass reference to refer either objects of the parent class or child class. The method that is called depends on the type of the object the reference refers. If it refers to a child class object then the overriding method of the child class is called. If it refers to a parent class object then the overridden method of the parent class is called. This phenomenon is popularly known as Dynamic method dispatch.

Output :

 


3. Miscellaneous Examples of Polymorphism

Note that these are minor topics in Polymorphism. The important ones are discussed above and deal with method overloading and method overriding.


3.1 Type Coercion

Sometimes the compiler converts the data types implicitly to avoid errors. This is called Polymorphic Type Coercion.

Output :

 


3.2 Operator Overloading

Operator overloading deals with same operator performing different operations depending on the context in which it is used. For example: + operator can be used for both mathematical addition and String Concatenation.

Output :

I called it a minor topic because Java doesn’t support user defined operator overloading.


4. Summary

  • Compile time polymorphism can be achieved by method overloading.
  • Run time polymorphism can be achieved by method overriding.
  • There are other ways to achieve polymorphism as well like operator overloading, type coercion etc.