Programs

Types of Polymorphism in Java [Static & Dynamic Polymorphism with Examples]

Summary:

In this article, you will learn Types of Polymorphism in Java with examples.

  • Static polymorphism (or compile-time polymorphism)
  • Dynamic Polymorphism (or run time polymorphism in Java)

Read more to know each in detail.

What is Polymorphism in Java?

One of the important concepts in Object Oriented Programming (OOP) is polymorphism which means that a single action can be performed in different ways. It is derived from the Greek words: poly and morphs meaning many and forms. The different forms exist when they are related through inheritance.

Polymorphism in Java creates a single method render() that behaves according to different shapes. A real-life example of polymorphism would be a woman who is a Vice President of a company, daughter, mother, sister, or wife. 

Check out our free courses to get an edge over the competition.

Like inheritance that inherits methods and attributes from a different class, polymorphism applies those methods and performs different tasks. An object is able to mold itself into various forms through polymorphism.

 This implies that polymorphism facilitates a single action to be performed in multiple ways. Because of polymorphism, the reusability of a code can be done. Polymorphism in Java reduces coupling and increases the readability of a code as well. Different types of polymorphism in Java helps to mold various types of data. 

That is, an entity can perform different operations in different scenarios. One of the most common uses of polymorphism in Object Oriented Programming is when a parent class reference is used to refer to a child class object.

This implies that an entity has the characteristics to operate differently according to the scenarios.  The ability of a class to provide different implementations of a method depends on the type of object that is passed to the method. You can also consider doing our Java Bootcamp course from upGrad to upskill your career.

Read more on various OOPs concepts and examples.

Polymorphism in Java can be achieved through three methods:

Method Overriding: If a superclass and a subclass consist of the same method, then method overriding refers to the process of overriding the method in the superclass by the method in the subclass. As a result, the same method will be used in different conditions performing different operations.

Java achieves Run Time Polymorphism in many ways, one of the ways is method overriding.  Method overriding, on the other hand, occurs when a derived class has a definition for one of the member functions of the base class.

Our learners also read: Learn java free!

Output of the program:

Java Programming Language

Common English Language

  1. Method Overloading: Method overloading refers to process of creation of methods with the same name but with different parameters. Examples include: void func() { … }, void func(int a) { … }, float func(double a) { … }, float func(int a, float b) { … }.

In the case of one or more methods with the same name and/or return types but different parameter lists, in that case, we say that we have “overloaded” the methods. In simple, two or more methods may have the same name if they differ in parameters (different number of parameters, different types of parameters, or both). These methods are called overloaded methods and this feature is called method overloading.

Output

**********

##########

  1. Operator overloading: Operator overloading is a concept in Java where an operator behaves differently with different operands. Examples include:
  • The operator “+” can be used both in numeric addition and string concatenation.
Numerical addition String concatenation
int a = 5;

int b = 6;

int sum = a + b;  // Output = 11

String first = “Python “;

String second = “Programming”;

name = first + second;  // Output = Python Programming

  • The operators &,|, and ! can be used for logical and bitwise overloading.

Featured Program for you: Fullstack Development Bootcamp Course

upGrad’s Exclusive Software and Tech Webinar for you –

SAAS Business – What is So Different?

 

Types of Polymorphism in Java

Object-Oriented Programming focuses on four basic concepts i.e. abstraction, encapsulation, inheritance, and polymorphism. Polymorphism is the ability to process objects differently on the basis of their class and data types. As discussed, that polymorphism is of different types, for it to cover different types of data. Nd polymorphism has properties and methods. 

There are two types of polymorphism in Java: compile time polymorphism and run time polymorphism in java. This java polymorphism is also referred to as static polymorphisms and dynamic polymorphisms.

1. Static polymorphism (or compile-time polymorphism)

Like most of the other OOP programming languages, Java polymorphism allows the incorporation of multiple methods within a class. The methods use the same name but the parameter varies. This represents the static polymorphism. This polymorphism is resolved during the compiler time and is achieved through the method overloading.  (Compile-time Polymorphism) Static Polymorphism in Java decides which method to execute during compile time. In static polymorphism, the object would behave differently for the same trigger. This is why multiple methods are incorporated into the same class.

  • The parameters number should vary.
  • The parameter types should be different.
  • Different order of parameters. For example, if a method accepts a string and a long, while the other method accepts a long and a string. However, this type of order makes it difficult for the API to understand.

Due to the difference in the parameters, every method has a different signature. The Java compiler has an idea of which method is called.

Learn Software Courses online from the World’s top Universities. Earn Executive PG Programs, Advanced Certificate Programs, or Masters Programs to fast-track your career.

Example of static polymorphism

One of the ways by which Java supports static polymorphism is method overloading. An example showing the case of method overloading in static polymorphism is shown below:

Example:

class SimpleCalculator

{

    int add(int a, int b)

    {

         return a+b;

    }

    int  add(int a, int b, int c)  

    {

         return a+b+c;

    }

}

public class Demo

{

   public static void main(String args[])

   {

  SimpleCalculator obj = new SimpleCalculator();

       System.out.println(obj.add(25, 25));

       System.out.println(obj.add(25, 25, 30));

   }

}

Output of the program

50

80

Explore Our Software Development Free Courses

2. Dynamic Polymorphism (or run time polymorphism in Java)

In this form of polymorphism in java, the compiler doesn’t determine the method to be executed. It’s the Java Virtual Machine (JVM) that performs the process at the run time. Dynamic polymorphism in Java refers to the process when a call to an overridden process is resolved at the run time. The reference variable of a superclass calls the overridden method. As the name dynamic connotes, dynamic polymorphism happens among different classes as opposed to static polymorphism. Dynamic polymorphism facilitates the overriding of methods in Java which is core for run-time polymorphism.

Understanding the process of Upcasting is crucial before understanding the concept of run time polymorphism. Upcasting refers to the process where an object of the child class is referred to by a reference variable of the superclass. Learn about polymorphism in PHP.

Example of Dynamic polymorphism (or run time)

Example1:

Two classes Bike and Splendor are created and the class of Splendor extends the class of Bike overriding its run() method. The run() method is called by the reference variable of the parent class. Since the subclass method is overriding the parent class method; the subclass method is invoked at run time. 

The program 

class Bike{  

 void run(){System.out.println(“running”);}  

}  

class Splendor extends Bike{  

  void run(){System.out.println(“walking safely with 30km”);}  

    public static void main(String args[]){  

    Bike b = new Splendor();//upcasting  

    b.run();  

  }  

}  

Output: walking safely with 60km

In-Demand Software Development Skills

Example 2

Two classes with the names of “ABC” and “XYZ” are created where XYZ is a child class and ABC is a parent class. Here, the method myMethod() of the parent class is overridden by the child class. The child class object is assigned to the parent class reference.

Also visit upGrad’s Degree Counselling page for all undergraduate and postgraduate programs.

Program:

class ABC{

   public void myMethod(){

System.out.println(“Overridden Method”);

   }

}

public class XYZ extends ABC{

   public void myMethod(){

System.out.println(“Overriding Method”);

   }

   public static void main(String args[]){

ABC obj = new XYZ();

obj.myMethod();

   }

}

Output

Overriding Method

Explore our Popular Software Engineering Courses

Conclusion

The concept of polymorphism in java is one of the most useful features in Object-Oriented Programming.  Further, the capability to invoke a method both at the static and the run time widens its applicability.

The idea behind bringing the concept of polymorphism is flexibility. Further the ability to process a large number of objects in a single reference variable, makes the coding a bit easier. Therefore, the concept should be used in the  daily coding tasks and embrace its effectiveness.

In this article, we discussed the various types of polymorphism in java example, like Static and Dynamic. Static polymorphism is a type of polymorphism that collects the information to call a method during compile time while dynamic polymorphism is a type of polymorphism that collects information to call a method at run time. Thus, this is the main difference between static and dynamic polymorphism

Read our Popular Articles related to Software Development

How is inheritance different from polymorphism?

Inheritance creates a new class that inherits the features of an existing class, whereas polymorphism allows a class to be defined in various ways. Polymorphism is used to apply to functions or methods, whereas inheritance is used to apply to classes. In object-oriented programming, inheritance promotes reusability and minimizes code length. Polymorphism lets the object choose the form of the function to implement both at compile (overloading) and run time (overriding). Single, hybrid, multiple, hierarchical, and multilevel inheritance are all possible. There are two types of polymorphism which are the compile-time polymorphism (overload) and run-time polymorphism (overriding).

What are OOPs?

Object-oriented programming, or OOP, is a programming framework based on objects. This paradigm divides data into objects (data fields) and uses classes to define the contents and behavior of those objects. Because of OOP's modular nature, programmers may create software in smaller, more manageable chunks rather than enormous blocks of sequential code. One of the most appealing features of OOP is its scalability, as objects and declarations have no bounds. Furthermore, the separation of data and procedure eliminates a typical issue in previous linear software languages.

What are the benefits of using Java?

Java has a syntax that is simple to develop, learn, maintain, and comprehend, and the code is simple to debug. It is an object-oriented programming language that allows users to increase the code's flexibility and reusability. Users may simply reuse the object in different programmes thanks to the OOPs idea. It also assists users in enhancing security by combining data and functions into a single unit that is not accessible to the outside world. Java also helps to organize larger modules into smaller ones, making them easier to comprehend. Because Java applications require a specific hardware infrastructure to execute, they are inexpensive to design and maintain.

Why is method overriding an example of polymorphism?

Calling of a function to the overridden method, polymorphism of this type is achieved by Method Overrdiing. On the contrary, Method Overriding happens when the derived class holds a definition for the member functions of the base class.

Can polymorphism be achieved through method overloading?

To say that method overriding or overloading is polymorphism would be incorrect because they are not. Rather, they facilitate the process, as polymorphism can be implemented using method overriding or overloading.

What is the benefit of polymorphism?

Reusing a code is one of the most important benefits. Once the classes have undergone the process of being written, tested, or implemented then reusing could help. It saves time and effort for the programmer. Also, one single variable can be used to store multiple types of data. Hence, it reduces the chances of error as it is easier to debug the code.

What are the advantages of Polymorphism?

Flexibility in the code can be achieved. Because various operations can be performed using methods with the same names according to requirements. The main benefit of using polymorphism is when we can provide implementation to an abstract base class or an interface.

What is binding in Java?

The connecting (linking) between a method call and method definition is called binding in java. There are two types of binding in java. They are as follows: a. Static Binding (also known as Early Binding). b. Dynamic Binding (also known as Late Binding).

How is inheritance different from polymorphism?

Inheritance creates a new class that inherits the features of an existing class, whereas polymorphism allows a class to be defined in various ways. Polymorphism is used to apply to functions or methods, whereas inheritance is used to apply to classes. In object-oriented programming, inheritance promotes reusability and minimizes code length. Polymorphism lets the object choose the form of the function to implement both at compile (overloading) and run time (overriding). Single, hybrid, multiple, hierarchical, and multilevel inheritance are all possible. There are two types of polymorphism which are the compiled-time polymorphism (overload) and run-time polymorphism (overriding).

What are OOPs?

Object-oriented programming, or OOP, is a programming framework based on objects. This paradigm divides data into objects (data fields) and uses classes to define the contents and behavior of those objects. Because of OOP's modular nature, programmers may create software in smaller, more manageable chunks rather than enormous blocks of sequential code. One of the most appealing features of OOP is its scalability, as objects and declarations have no bounds. Furthermore, the separation of data and procedure eliminates a typical issue in previous linear software languages.

What are the benefits of using Java?

Java has a syntax that is simple to develop, learn, maintain, and comprehend, and the code is simple to debug. It is an object-oriented programming language that allows users to increase the code's flexibility and reusability. Users may simply reuse the object in different programmes thanks to the OOPs idea. It also assists users in enhancing security by combining data and functions into a single unit that is not accessible to the outside world. Java also helps to organize larger modules into smaller ones, making them easier to comprehend.Because Java applications require a specific hardware infrastructure to execute, they are inexpensive to design and maintain.

Want to share this article?

Plan Your Software Development Career Now.

Leave a comment

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

Our Popular Software Engineering Courses

Get Free Consultation

Leave a comment

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

×
Get Free career counselling from upGrad experts!
Book a session with an industry professional today!
No Thanks
Let's do it
Get Free career counselling from upGrad experts!
Book a Session with an industry professional today!
Let's do it
No Thanks