The IoT Academy Blog

What Is Polymorphism in Java and How to Implement It?

  • Written By  

  • Published on October 25th, 2022

Table of Contents [show]

 

 

Introduction

 

One of the key Java concepts you must learn to comprehend the object-oriented programming paradigm is polymorphism. A Java feature called polymorphism gives an entity the capacity to operate from various viewpoints.

 

What is Polymorphism?

 

Polymorphism refers to the existence of various forms. Polymorphism is the capacity of a message to manifest in more than one form, to put it simply.

An example is drawn from actual life Polymorphism

A person can simultaneously possess multiple traits. He juggles being a father, a husband, and a worker as a guy. As a result, a person's behaviour can vary depending on the circumstance. Polymorphism is the term for this.

One of the key components of object-oriented programming is polymorphism. We are able to carry out a single activity in various ways because of polymorphism. Polymorphism, in other terms, enables you to specify a single interface with a variety of implementations. Polymorphs refer to numerous different forms because the term "poly" signifies many different.

 

 

Our Learners Also Read: What is the Java Full Stack Development Course?

 

Polymorphism in Java

 

In Java, the concept of polymorphism allows us to carry out a single action in various ways. Greek terms poly and morphs are the roots of the word polymorphism. Poly means numerous, and morphs means different forms. Polymorphism entails a diversity of forms.

Compile-time polymorphism and runtime polymorphism are the two types of polymorphism used in Java. In Java, method overloading and method overriding are two ways to implement polymorphism.

Java's overloading of static methods is an illustration of compile-time polymorphism. Here, we'll concentrate on Java's runtime polymorphism.

 

“`

// Parent class to illustrate run-time polymorphism

class Parent {

  // creating print method

  void print() {

    System.out.println("Hi I am parent");

  }

}

// Child class extends Parent class

class Child extends Parent {

  // overriding print method

  void print() {

    System.out.println("Hi I am children");

  }

}

// Overload class to illustrate compile-time polymorphism

class Overload {

  // Creating a statement method

  void statement(String name) {

    System.out.println("Hi myself " + name);

  }

  // overloading statement method

  void statement(String fname, String lname) {

    System.out.println("Hi myself " + fname + " " + lname);

  }

}

public class Main {

  public static void main(String[] args) {

    // creating instance of parent

    Parent obj1;

    obj1 = new Parent();

    obj1.print();

    obj1 = new Child();

    obj1.print();

 

    // creating instance of overload

    Overload obj2 = new Overload();

    obj2.statement("Soham.");

    obj2.statement("Soham", "Medewar.");

  }

}

“`

 

Polymorphism Types

 

In Java, there are two main kinds of polymorphism. As follows:

  • Compile-time polymorphism
  • Run-time polymorphism

 

Compile-Time Polymorphism

 

At the compile-time stage, a typical Java Application meets compile-time polymorphism. Overloading of methods occurs in this case at compile time. Two examples of compile-time polymorphism are as follows:

 

Method Overloading

 

Method When a class contains two or more methods with the same name, this is known as overloading. However, the number of parameters in a specific method determines how it is implemented.

 

Operator Overload

 

Method for operator overload When a class contains two or more methods with the same name, this is known as overloading. However, the amount of parameters in the method specification determines how a certain method is implemented.

Operator overloading is not supported in Java in order to prevent confusion.

 

Run-Time Polymorphism

 

Runtime polymorphism is a technique in which a programme is executed in real-time. The rewrite resolution takes place during this phase of execution. Runtime polymorphism takes place twice.

 

Method Override

 

Approach Overrides Approach Through a process called overriding, a child class can implement a certain method that is already present in the parent class.

 

Operator Override

 

By using the method known as "operator overriding," you can define an operator with the same signature in both a parent and a child class but with distinct operational capabilities.

Operator overriding is not permitted in Java to prevent ambiguities.

 

Characteristics of Polymorphism

 

In addition to method overloading and method overriding, polymorphism has other properties, as discussed below.

  • Coercion
  • Internal operator overload
  • Polymorphic variables or parameters
  • Subtype polymorphism

 

Coercion

 

Consider two variables, one with an integer data type and the other with a double data type, to help you better comprehend this. We receive a type error if we add these two numbers.

A smaller data type is automatically cast to a more significant data type when necessary via Java's built-in coercion functionality, which helps to prevent such problems. In this instance, the integer number will first be converted to a double value before the addition is carried out. So, a type error is prevented.

Coercion is the implicit conversion of one data type to another without altering its context. To prevent type errors, this conversion type is used.

In other words, coercion happens when data is present in one data type but a different data type is required by its environment.

Internal operator overload

Java does not support operator overloading, as the article explains. Internal operator overloading, when one operator is utilised in multiple ways, is still a thing in Java. Here, a static polymorphism feature is evident.

The "+" symbol in Java concatenates two strings or adds two numbers.

 

Polymorphic Variables or Parameters

 

The checker example is included in the definition of polymorphism, as previously stated. A woman is referred to as a mother if she has a kid, a sister if she has siblings, and a wife if she has a spouse. As a result, the queen can take on numerous meanings depending on the circumstances, making checkers a polymorphic variable.

Polymorphic variables are those that take on different values depending on the situation. Because each object or instance variable in Java has an IS-A relationship with its own classes and subclasses, each object or instance variable is a polymorphic variable.

Polymorphic variables are those that take on distinct values at various points during execution.

According to parameter polymorphism, a method name can be connected to several parameters and return types whereas an array name can be connected to various types of elements.

 

Subtype Polymorphism

 

Consider a zoo with four different tigers, three different lions, and two different elephants. The information about the animals has to be kept in a list. Using the subtype polymorphism attribute, we can store data. Assume that the parent class of animals includes the tiger, lion, and elephant.

Traditionally, we create an object of the tiger class and store the information. We do the same for all animals. But in subtype polymorphism, we create an array of animal classes and then cast each tiger, lion, and elephant object to an animal class. Store the transferred objects in the animal class field.

The ability to use a subclass instead of a superclass is called subtyping polymorphism. In other words, subtype polymorphism refers to upcasting and late binding. Upcasting is merely dynamic binding or overriding, late binding is simply typecasting of a child object to a parent object.

 

Advantages of Polymorphism

 

  • One of the main benefits of polymorphism is code reuse; once a class is defined, it may be used repeatedly to produce an object.
  • Code readability is improved in compile-time polymorphism since nearly identical functions can have the same name, making them simple to comprehend.
  • The identical method can be created using runtime polymorphism in both the parent and child classes.
  • Debugging code is simple. You can store intermediate results from the code's execution in any position in memory, where they can later be accessed by other programme elements. Debugging is facilitated by polymorphism, which provides the calculation with the necessary regularity and structure.

 

Conclusion

 

  • Polymorphism is one of the four elements of Object-Oriented Programming.
  • By correctly implementing polymorphism, class designs can be made extensible and versatile.
  • The two primary types of polymorphism are runtime polymorphism and compile-time polymorphism.
  • Runtime polymorphism is achieved via method overriding, whereas compile-time polymorphism is accomplished using method overloading.
  • Java enables forced polymorphism and parametric polymorphism in addition to runtime and compilation.
  • We can reuse code without recompiling it if we use inheritance and method overriding.
  • Method overloading is a strategy for accessing related functions with a similar name.
  • Coercion polymorphism is used to achieve internal operator overloading.
  • A feature of method overriding allows a subclass to access all the generic definitions provided by the superclass while also adding more specific definitions via overridden methods.

 

About The Author:

logo

Digital Marketing Course

₹ 9,999/-Included 18% GST

Buy Course
  • Overview of Digital Marketing
  • SEO Basic Concepts
  • SMM and PPC Basics
  • Content and Email Marketing
  • Website Design
  • Free Certification

₹ 29,999/-Included 18% GST

Buy Course
  • Fundamentals of Digital Marketing
  • Core SEO, SMM, and SMO
  • Google Ads and Meta Ads
  • ORM & Content Marketing
  • 3 Month Internship
  • Free Certification
Trusted By
client icon trust pilot
1whatsapp