Training Outcomes Within Your Budget!

We ensure quality, budget-alignment, and timely delivery by our expert instructors.

Share this Resource

Table of Contents



Polymorphism is a key concept of Object-Oriented Programming (OOP) that allows Java to use one class for multiple purposes. The word “Polymorphism” means many forms. It reflects how Java classes can provide different behaviours for a method.

According to Glassdoor, the average salary of a Java Developer in the UK is about £55,000 annually. It is a great job with lots of perks and benefits. If you want to become a Java Developer, then you should be familiar with important concepts like Polymorphism in Java.

That's exactly what this blog is all about. In this blog, you will learn Polymorphism in Java and its different types with detailed examples. Let's dive in to learn more!

Table of Contents

1) What is Polymorphism in Java?

2) Types of Polymorphism in Java

3) Examples of Polymorphism in Java

4) Compile-time Polymorphism vs. Run-time Polymorphism: Key differences

5) Advantages of Polymorphism in Java

6) Disadvantages of Polymorphism in Java

7) Characteristics of Polymorphism

8) Conclusion

What is Polymorphism in Java?

Polymorphism in Java is a feature which enables Java classes to take on multiple forms of implementations. This feature is why Java is known as an Object-Oriented rather than an Object-Based language. Polymorphism comes into play when many classes are interrelated through the concept of Inheritance.   

Inheritance exists between parent and child classes, where both classes contain the same method name accepting different parameters. This ability to allow the same method name to take the input of different parameters enables the reusability of code for the developer at compile-time.

Learn to map Inheritance by using the Hibernate Query Language (HQL). Sign up for the Hibernate Training now! 

Types of Polymorphism in Java

In general, Polymorphism in Java is of two different types. Let’s take a detailed look at them below:

 Types of Polymorphism in Java

Compile-time Polymorphism in Java

Compile-time Polymorphism occurs when Java resolves the Polymorphism at the time of compilation. This resolution is achieved using Method Overloading.

Method Overloading:

Overloading is a Java feature that allows a class to have multiple methods working differently with the same name and distinct parameters. Java methods can also be overloaded by changing the type or number of parameters. Let’s have a look at this example which illustrates Method Overloading:
 


public class Calculator
{
public int add(int num1, int num2)
{
return num1 + num2;
}
public int add(int num1, int num2, int num3)
{
return num1 + num2 + num3;
} public double add(double num1, double num2)
{
return num1 + num2;
}
}


In the above example, the class ‘Calculator’ contains three methods named ‘add()’ with type public. These methods perform the same addition operation, with changes in the number and data type of the integers. The data type ‘public’ enables access to these methods outside their scope of definitions. Although the methods are named the same, Java will understand which method is being called based on the type and number of parameters passed as the input. 

Learn to map Inheritance by using the Hibernate Query Language (HQL). Sign up for the Hibernate Training course now! 

Run-time or Polymorphism in Java 

Run-time Polymorphism is a feature of Java where the invocation to the method being overridden is resolved at run-time. Contrary to Compile-time Polymorphism, Runtime Polymorphism is achieved by overriding the method.

Method Overriding:

In Method Overriding, the child or sub-class will contain a method by the same name as the parent class, where the child class’s method will be run as an override on the parent class method. The child class will have an ‘IS-A’ relationship with the parent class, demonstrating the Inheritance concept.

The sub-class must have implemented the same method to override the parent class, which is a protocol to perform Method Overriding in Java to demonstrate the concept of Polymorphism.   
As an example, 
 

class Animal
{
public void move()
{
System.out.println("Animals can move");
}
}
class Dog extends Animal
{
public void move()
{
System.out.println("Dogs can run and walk");
}
}
public class TestDog { public static void main(String args[])
{
Animal a = new Animal(); // Animal reference and object
Animal b = new Dog(); // Animal reference but Dog object
a.move(); // calls the method in the Animal class
b.move(); // calls the method in the Dog class
}
}


In the above example, the parent class is ‘Animal’ and its sub-class ‘Dog’. The ‘Animal’ parent class has a method named ‘move()’, also implemented in the ‘Dog’ sub-class. The Animal and Dog classes demonstrate an ‘IS-A’ relationship of Inheritance following the method overriding protocol. The program prints the output “Dogs can run and walk” because the Dog() class implements its move() method after the move() in ‘Animal’. 


Java Training
 

Examples of Polymorphism in Java 

In this section, let’s explore some examples of Polymorphism in Java:

Example 3:
 


class MethodOverloading
{
private static void display(int a)
{
System.out.println("Arguments: " + a);
}
private static void display(int a, int b)
{
System.out.println("Arguments: " + a + " and " + b);
}
public static void main(String[] args)
{
display(1);
display(1, 4);
}
}


The above example shows a class ‘MethodOverloading’, which contains two methods named ‘display()’. The first accepts one parameter of type ‘int’, and the second accepts two of type ‘int’. The main() method invokes each display() method consecutively and prints the outputs as follows:

“Arguments: 1” 

“Arguments: 1 and 4” 

 As illustrated in the program above, the program prints both method outputs in their order of declaration in the program. 
 

class MethodOverloading
{
// this method accepts int
private static void display(int a)
{
System.out.println("Got Integer data.");
}
// this method accepts String object
private static void display(String a)
{
System.out.println("Got String object.");
}
public static void main(String[] args)
{
display(1);
display("Hello");
}
}


The above program will print the following output: 

“Got Integer Data.” 

“Got String object.” 

In this example, the data types of the parameters of both display() methods are different, where one is of the Integer data type, and the other is of a String data type. The input values are provided inside the main() method, and Java accordingly recognises the data types of the inputs.

However, notice that the output of each method is a string, which means that if the data type is satisfied with each input in the main() method, then the output statement will be printed as it is.   

Compile-time Polymorphism vs. Run-time Polymorphism: Key differences

Compile-time Polymorphism happens when the compiler decides which method to execute based on the number, type, and order of the arguments. Run-time Polymorphism happens when the actual method to execute is determined at run-time based on the object's type. Let's explore the key differences between them:

1) Method call handling

Compile-time Polymorphism: The compiler manages method calls during compilation.

Run-time Polymorphism: The compiler cannot control method calls during run-time, they are determined dynamically.

2) Flexibility

Compile-time Polymorphism: It is less flexible as it must handle all method calls during compilation, and method calls are fixed at that time.

Run-time Polymorphism: Offers higher flexibility as it handles method calls dynamically at run-time, allowing for dynamic adaptation.

3) Execution period

Compile-time Polymorphism: Generally, it has a shorter execution period because method calls are resolved at compile time.

Run-time Polymorphism: Often involves a longer execution period due to dynamic method resolution during run-time.

4) Method call alignment

Compile-time Polymorphism: Integrating the right method call with the proper method is determined and fixed during compile-time.

Run-time Polymorphism: Combining the correct method call with the right method occurs dynamically at run-time.

5) Occurrence

Compile-time Polymorphism: It occurs during Method Overloading (having multiple methods in the same class with different parameter lists) and Operator Overloading (redefining operators for user-defined classes).

Run-time Polymorphism: Primarily occurs through Method Overriding (redefining a method in a subclass that is already defined in the parent class), typically in the context of Inheritance.

These differences highlight the fundamental distinctions between Compile-time Polymorphism and Run-time Polymorphism in Java.

Refer to Our Java Interview Questions and Answers to get through the Interviews with ease

Advantages of Polymorphism in Java

Polymorphism in Java has many advantages to the programming environment in the following ways: 

1) Java methods with the same names and parameters allow programmers to reuse parts of the code depending on the Inheritance between classes.  

2) Referencing the Calculator example above in this blog, the add () method can exist with different functionalities.  

3) Inheritance between parent and child classes can be implemented through Polymorphism, like in this blog's Animal program example above.  

4) Inheritance works in tandem with Method Overriding to allow the reuse of code from available classes to eliminate the re-compilation of the program. 

Disadvantages of Polymorphism in Java

The feature of Polymorphism in Java also has many disadvantages in the following ways: 

1) The functionality of multiple methods with the same names and different parameters decreases the overall readability of the program for the developer.  

2) Even developers face challenges themselves while implementing Polymorphism in the codes.  

3) Run-time Polymorphism takes decisions to invoke variables when the program has to run, which degrades performance significantly. 

Characteristics of Polymorphism

Polymorphism encompasses several characteristics beyond Method Overloading and Method Overriding. Let's explore some of them below:

1) Coercion

Coercion is a characteristic of Polymorphism that involves the automatic conversion of one data type into another data type. This conversion is performed automatically by the program to prevent type errors in the code. In languages like C and Java, data type conversions can be categorised into two types: implicit and explicit.

Implicit type conversion: This type of conversion is done automatically within the program and is often referred to as coercion. For example, if an operation involves an integer and a floating-point number, the compiler will implicitly convert the integer into a floating-point value. This is necessary to ensure type compatibility and avoid errors. Here's an example:

 

class CoercionExample {

   public static void main(String[] args) {

     double area = 3.14 * 5 * 7;

     System.out.println(area);

     String s = "happy";

     int x = 5;

     String word = s + x;

     System.out.println(word);

   }

}

 

Explicit type conversion: Explicit type conversion involves manually converting one data type into another data type. This is typically done when there is a need to override the default automatic type conversion or when it may result in a loss of data. In Java, explicit type casting can be achieved using casting operators like (datatype).

2) Internal Operator Overloading

Polymorphic variables are variables that can hold values of different types during the execution of a program. In Java, these variables are often associated with object or instance variables and represent a key aspect of Polymorphism.

These variables are capable of having an IS-A relationship with their own class and its subclasses. This allows them to refer to objects of different classes during program execution. Let's explore an example of Internal Operator Overloading:
 

class OperatorOverloadingExample {

   public static void main(String[] args) {

     String s = "happy";

     String s1 = "world";

     int x = 5;

     int y = 10;

     System.out.println(s + s1); // String concatenation

     System.out.println(x + y); // Numerical addition

   }

}

 

Take your Java skills to the next level with our Java Engineer Training – Sign up now!

3) Polymorphic variables or parameters

Polymorphic variables are variables that can hold values of different types during the execution of a program. In Java, these variables are often associated with object or instance variables and represent a key aspect of Polymorphism.

These variables can also have an IS-A relationship with their own class and its subclasses. So, it lets them refer to objects of different classes during program execution. Here's an example:
 

class Shape {

   public void display() {

     System.out.println("A Shape.");

   }

}

class Triangle extends Shape {

   public void display() {

     System.out.println("I am a triangle.");

   }

}

public class PolymorphicVariableExample {

   public static void main(String[] args) {

     Shape obj;

     obj = new Shape();

     obj.display(); // Calls the display method of Shape class

     obj = new Triangle();

     obj.display(); // Calls the display method of Triangle class

   }

}

 

Conclusion

We hope you read and understand everything about Polymorphism in Java. It is a powerful concept that allows us to perform a single action in different ways. By understanding its principles, we can create more scalable and robust applications.

Learn advanced Java concepts with our Introduction to Java EE Training – Sign up now!

Frequently Asked Questions

What are the advantages of Java Polymorphism? faq-arrow

Java Polymorphism offers several benefits, including code reusability, flexibility, and extensibility. It allows developers to write more versatile and adaptable code by enabling objects of different classes to be treated uniformly through inheritance and interfaces, promoting easier maintenance and scalability.

What do overloading and overriding mean in Java? faq-arrow

In Java, overloading refers to defining multiple methods in the same class with different parameter lists, allowing methods with the same name but different arguments. Overriding involves redefining a method in a subclass that is already defined in the parent class. It enables the customisation of inherited behaviour to suit specific requirements.

What are the other resources provided by The Knowledge Academy? faq-arrow

The Knowledge Academy takes global learning to new heights, offering over 30,000 online courses across 490+ locations in 220 countries. This expansive reach ensures accessibility and convenience for learners worldwide.

Alongside our diverse Online Course Catalogue, encompassing 17 major categories, we go the extra mile by providing a plethora of free educational Online Resources like News updates, Blogs, videos, webinars, and interview questions. By tailoring learning experiences further, professionals can maximise value with customisable Course Bundles of TKA.
 

What is the Knowledge Pass, and how does it work? faq-arrow

The Knowledge Academy’s Knowledge Pass, a prepaid voucher, adds another layer of flexibility, allowing course bookings over a 12-month period. Join us on a journey where education knows no bounds.

What are related courses and blogs provided by The Knowledge Academy? faq-arrow

The Knowledge Academy offers various Java Courses, including Java Programming Course, JavaScript for Beginners and Java Engineer Training. These courses cater to different skill levels, providing comprehensive insights into Java Methodologies.

Our Java Blogs cover a range of topics related to Java, offering valuable resources, best practices, and industry insights. Whether you are a beginner or looking to advance your Java Programming skills, The Knowledge Academy's diverse courses and informative blogs have you covered.
 

Upcoming Programming & DevOps Resources Batches & Dates

Date

building Java Programming

Get A Quote

WHO WILL BE FUNDING THE COURSE?

cross

OUR BIGGEST SUMMER SALE!

Special Discounts

red-starWHO WILL BE FUNDING THE COURSE?

close

close

Thank you for your enquiry!

One of our training experts will be in touch shortly to go over your training requirements.

close

close

Press esc to close

close close

Back to course information

Thank you for your enquiry!

One of our training experts will be in touch shortly to go overy your training requirements.

close close

Thank you for your enquiry!

One of our training experts will be in touch shortly to go over your training requirements.