Polymorphism in Java: Compile time and Runtime Polymorphism

Shailendra Chauhan  13 min read
22 Sep 2023
Intermediate
834 Views

Polymorphism in Java: An Overview

In this article, we'll learn the concepts of polymorphism in Java example, Java Polymorphism. Polymorphism is one of the most important and unique features in programming, especially in the context of a Java tutorial. In the word Polymorphism, "Poly" stands for many, and "Morph" stands for forms, thus, it means many forms. As an example, we can be an engineer and a mother, a sister, and a daughter as well. Here, a single woman is performing various roles in life, illustrating how Polymorphism performs the same role in programming.

What is Polymorphism in Java?

Polymorphism in Java is an utmost importance feature in Java. It is also one of the essential pillars of object-oriented programming Java. It represents a single entity in multiple forms such as constructor overloading, method overloading, etc. Java conditional statements play a crucial role in enabling developers to implement polymorphism effectively.

Different types of Polymorphism in Java

There are two types of Polymorphism in Java, which are

  1. Compile time Polymorphism
  2. Run time Polymorphism

Compile time Polymorphism in Java

Compile time polymorphism in Java resolves the problem regarding compile time with the help of "Method overloading" and "Constructor overloading".

Method overloading in Java

Method overloading in Java works for two or more methods or functions that are stored in the same class with the same name but different parameters and arguments.

Example

class Method_Overloading
{
    //Method Overloading by changing the number of arguments (or parameters)

//Method 1
    double figure(double l, double b) //two arguments or parameters
    {
        return (l*b);
    }
    double figure(double s) //one argument or parameter
    {
        return (s*s);
    }

//Method 2
    public static void main(String[] args)
    {
        Method_Overloading obj = new Method_Overloading();
        System.out.println("Area of Rectangle: " +obj.figure(5.55, 6.78));
        System.out.println("Area of Square: " +obj.figure(3.45));
    }
}

Output:

Area of Rectangle: 37.629
Area of Square: 11.90250000000002

Constructor overloading in Java:

Constructor overloading happens in Java when more than one constructor is declared inside a class but with different parameters. If an object in a class is created by using a new keyword, it generates a constructor in that class. In this Guide to Java, we'll explore how constructor overloading works and its significance in object-oriented programming.

Example

// Java program to demonstrate the
// working of operator overloading
public class SCHOLAR-HAT 
          {
 // function for adding two integers
 void add(int a, int b)
 {
  int sum = a + b;
  System.out.println(" Addition of two integer :"
      + sum);
 }

 // function for concatenating two strings
 void add(String s1, String s2)
 {
  String con_str = s1 + s2;
  System.out.println("Concatenated strings :"
      + con_str);
 }
 public static void main(String args[])
 {
  SCHOLAR-HAT obj = new SCHOLAR-HAT();
  // addition of two numbers
  obj.add(10, 10);
  // concatenation of two string
  obj.add("Operator ", " overloading ");
 }
}

 Output

Addition of two integer :20
Concatenated strings :Operator overloading 

Runtime Polymorphism in Java

Runtime Polymorphism specifies the depiction of run time by using overriding.

Method overriding in Java

This particular method in Java redefines a superclass method by generating the same name, parameters, and data types in a subclass.

Example

//A Simple made up Instance to show method overriding in Java
class Waka_Waka_Song
{
    Waka_Waka_Song()
    {
        System.out.println("Song--Initializing Waka Waka by Shakira...");
    }
    public void play()
    {
        System.out.println("Song-- Playing...");
    }
}

//Spotify wants Waka Waka song on their Platform
class Spotify extends Waka_Waka_Song
{
    Spotify()
    {
        System.out.println("Spotify...");
    }
    public void play()
    {
        System.out.println("Spotify-- Playing.. ");
    }
}

//Amazon_Music wants Waka Waka song on their Platform
class Amazon_Music extends Waka_Waka_Song
{
    Amazon_Music()
    {
        System.out.println("Amazon Music...");
    }
    public void play()
    {
        System.out.println("Amazon Prime-- Playing...");
    }
}

//A User Playing songs on Spotify and then Amazon Music
class User
{
    public static void main(String[] args)
    {
        System.out.println("Playing Waka Waka on Spotify... ");
        Spotify s = new Spotify();
        s.play();
        System.out.println("\nPlaying Waka Waka on Amazon Music");
        Amazon_Music p = new Amazon_Music();
        p.play();
    }
}

Output

Playing Waka Waka on Spotify…
Song - - Initializing Waka Waka by Shakira…
Spotify…
Spotify- - Playing . .
Playing Waka Waka on Amazon Music
Song - - Initializing Waka Waka by Shakira…
Amazon Music …
Amazon Prime- - Playing … 

Java Operator Overloading

  • Depending on the operands, operators like + in Java behave differently.
  • Java's operator overloading permits polymorphism, in which operators behave differently depending on the kinds of operands, improving the readability of the code.
  • Contrary to languages like C++, Java does not provide user-defined operator overloading.
  • In Java, operators are predefined and have fixed behaviors based on the types of inputs. For user-defined classes or types, specific operator overloads are not permitted.

What are Polymorphism Variables?

  • If a variable can refer to different values under different conditions, it is said to be polymorphic.
  • The behavior of polymorphic variables in Java is represented by object variables (also known as instance variables).
  • It's because a class's object variables can refer to both objects from that class and objects from its subclasses.

Why use Polymorphism in Java?

Java's polymorphism makes it easy to create methods that can correctly handle a wide variety of functions with the same name. We can use polymorphism to improve the consistency of our code.

Advantages of Polymorphism in Java

  • Reusable classes can be created, tested, and implemented.
  • Reusing old code helps programmers save time.
  • Changes can be made without having an impact on the original code.
  • Enables the storage of numerous data values in a single variable.
  • Independent changes can be made to values that a subclass inherits from a superclass.
  • The superclass and other subclasses are unaffected by changes to the subclass variable.
  • Debugging is made simpler by fewer lines of code.
  • Makes it easier for programmers to find and fix problems.

Characteristics of Polymorphism

Other than Method Overloading and Method Overriding, polymorphism exhibits a wide range of other characteristics. They consist of:

  1. Coercion
  2. Internal Operator Overloading
  3. Polymorphic Variables or Parameters

1. Coercion

  • Coercion involves the implicit conversion of one object type into another, automatically avoiding type mistakes.
  • The conversion of data types between various types is supported by programming languages like C, Java, etc.
  • Conversions between data types can be implicit or explicit.
  • The program does implicit type conversion, commonly referred to as coercion.
  •  When an integer operand is combined with a float operand, the compiler implicitly transforms the integer to a float to avoid type problems.

2. Internal Operator Overloading

  • Making an operator or symbol do several operations depending on the situation or the types of operands it works on is known as operator overloading.
  • The same operator or symbol might behave in a variety of ways based on the operands in static polymorphism, which is related to this phenomenon.
  • Java does not provide user-defined operator overloading, a feature that allows users to specify unique actions for operators with various operand types.
  • Java internally overloads some operators, enabling them to function differently in some circumstances.
  • To address certain programming requirements, operator overloading enables programmers to utilize operators or method names as if they were user-defined types.
  • As an example, the Java '+' operator can be used for both addition (with operands of the same data type) and string concatenation (with operands of the string type).
  • The expressiveness and functionality of the code are improved by the flexibility of the operator usage.

3. Polymorphic Variables or Parameters

  • Polymorphic variables are represented in Java by object or instance variables.
  • A class's object variables may display an IS– A polymorphic relationship with both their own class and its subclasses.
  • A variable that can store several types of values while a program is running is said to be polymorphic.
  • When a class is declared in Java, parametric polymorphism enables field names to be associated with various types.
  • Additionally, it makes it possible for method names to be linked to various argument and return types, improving the flexibility and reusability of code design.

FAQs

1. What is polymorphism in Java and its types?

Java objects can have various forms thanks to polymorphism. Compile-time (method overloading) and run-time (method overriding) polymorphism are two of its kinds.

2. What is overloading and overriding polymorphism in Java?

While overriding polymorphism takes place when a subclass offers a specific implementation for a method inherited from its superclass, overloading polymorphism entails declaring numerous methods with the same name in a class that differ in their parameter lists.

3. What are the two main types of polymorphism?

Compile-time (static) and run-time (dynamic) polymorphism are the two primary types of polymorphism.

4. What is the difference between polymorphism and inheritance?

Inheritance is concerned with the relationship between classes, whereas polymorphism is concerned with the behavior of objects. One of the mechanisms that permits polymorphism is inheritance.

5. What are the two types of overloading?

The two types of overloading are operator overloading, which Java does not enable for user-defined operators, and method overloading, in which methods in a class have the same name but distinct parameter lists.

Summary

In this comprehensive Java tutorial, the definition of polymorphism in Java including its type has been discussed vastly. How can you achieve runtime polymorphism has also been highlighted in this article. The definition of Runtime and Compile time Polymorphism with examples has been evaluated in this article, providing a comprehensive understanding of these concepts for Java Certification.

Share
About Author
Shailendra Chauhan (Microsoft MVP, Founder & CEO at DotNetTricks)

Shailendra Chauhan is the Founder and CEO at ScholarHat by DotNetTricks which is a brand when it comes to e-Learning. He provides training and consultation over an array of technologies like Cloud, .NET, Angular, React, Node, Microservices, Containers and Mobile Apps development. He has been awarded Microsoft MVP 8th time in a row (2016-2023). He has changed many lives with his writings and unique training programs. He has a number of most sought-after books to his name which has helped job aspirants in cracking tough interviews with ease.
Accept cookies & close this