The Wayback Machine - https://web.archive.org/web/20250212221737/https://www.geeksforgeeks.org/polymorphism-in-java/
Open In App

Polymorphism in Java

Last Updated : 09 Jan, 2025
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Share
Report
News Follow

The word ‘polymorphism’ means ‘having many forms’. In Java, polymorphism refers to the ability of a message to be displayed in more than one form. This concept is a key feature of Object-Oriented Programming and it allows objects to behave differently based on their specific class type.

Real-life Illustration of Polymorphism in Java: A person can have different characteristics at the same time. Like a man at the same time is a father, a husband, and an employee. So the same person possesses different behaviors in different situations. This is called polymorphism.

Example: A Person Having Different Roles

Java
// Base class Person
class Person {
  
    // Method that displays the 
    // role of a person
    void role() {
        System.out.println("I am a person.");
    }
}

// Derived class Father that 
// overrides the role method
class Father extends Person {
  
    // Overridden method to show 
    // the role of a father
    @Override
    void role() {
        System.out.println("I am a father.");
    }
}

public class Main {
    public static void main(String[] args) {
      
        // Creating a reference of type Person 
        // but initializing it with Father class object
        Person p = new Father();
        
        // Calling the role method. It calls the 
        // overridden version in Father class
        p.role();  
    }
}

Output
I am a father.

Explanation: In the above example, the Person class has a method role() that prints a general message. The Father class overrides role() to print a specific message. The reference of type Person is used to point to an object of type Father, demonstrating polymorphism at runtime. The overridden method in Father is invoked when role() is called.

Types of Java Polymorphism

In Java Polymorphism is mainly divided into two types: 

  • Compile-Time Polymorphism
  • Runtime Polymorphism
poly

1. Compile-Time Polymorphism

Compile-Time Polymorphism in Java is also known as static polymorphism. This type of polymorphism is achieved by function overloading or operator overloading. 

Note: But Java doesn’t support the Operator Overloading.

Java Polymorphism

Method Overloading

Method overloading in Java means when there are multiple functions with the same name but different parameters then these functions are said to be overloaded. Functions can be overloaded by changes in the number of arguments or/and a change in the type of arguments.

Example: Method overloading by changing the number of arguments

Java
// Method overloading By using
// Different Types of Arguments 

// Class 1
// Helper class
class Helper {

    // Method with 2 integer parameters
    static int Multiply(int a, int b)
    {
        // Returns product of integer numbers
        return a * b;
    }

    // Method 2
    // With same name but with 2 double parameters
    static double Multiply(double a, double b)
    {
        // Returns product of double numbers
        return a * b;
    }
}

// Class 2
// Main class
class Geeks
{
    // Main driver method
    public static void main(String[] args) {
      
        // Calling method by passing
        // input as in arguments
        System.out.println(Helper.Multiply(2, 4));
        System.out.println(Helper.Multiply(5.5, 6.3));
    }
}

Output
8
34.65

Subtypes of Compile-time Polymorphism:

  • Function Overloading: It is a feature in C++/Java where multiple functions can have the same name but with different parameter lists. The compiler will decide which function to call based on the number and types of arguments passed to the function.
  • Operator Overloading: It is a feature in C++ where the operators such as +, -, *, etc. can be given additional meanings when applied to user-defined data types.
  • Template: It is a powerful feature in C++ that allows us to write generic functions and classes. A template is a blueprint for creating a family of functions or classes.

2. Runtime Polymorphism

Runtime Polymorphism in Java known as Dynamic Method Dispatch. It is a process in which a function call to the overridden method is resolved at Runtime. This type of polymorphism is achieved by 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. That base function is said to be overridden.

Method Overriding

Java
// Java Program for Method Overriding

// Class 1
// Helper class
class Parent {

    // Method of parent class
    void Print() {
        System.out.println("parent class");
    }
}

// Class 2
// Helper class
class subclass1 extends Parent {

    // Method
    void Print() { 
      System.out.println("subclass1"); 
    }
}

// Class 3
// Helper class
class subclass2 extends Parent {

    // Method
    void Print() {
        System.out.println("subclass2");
    }
}

// Class 4
// Main class
class Geeks {

    // Main driver method
    public static void main(String[] args) {

        // Creating object of class 1
        Parent a;

        // Now we will be calling print methods
        // inside main() method
        a = new subclass1();
        a.Print();

        a = new subclass2();
        a.Print();
    }
}

Output
subclass1
subclass2

Explanation: In the above example, when an object of a child class is created, then the method inside the child class is called. This is because the method in the parent class is overridden by the child class. Since the method is overridden, This method has more priority than the parent method inside the child class. So, the body inside the child class is executed.

Subtype of Run-Time Polymorphism

Virtual Functions: It allows an object of a derived class to behave as if it were an object of the base class. The derived class can override the virtual function of the base class to provide its own implementation. The function call is resolved at runtime, depending on the actual type of the object.

Advantages of Polymorphism

  • Increases code reusability by allowing objects of different classes to be treated as objects of a common class.
  • Improves readability and maintainability of code by reducing the amount of code that needs to be written and maintained.
  • Supports dynamic binding, enabling the correct method to be called at runtime, based on the actual class of the object.
  • Enables objects to be treated as a single type, making it easier to write generic code that can handle objects of different types.

Disadvantages of Polymorphism

  • Can make it more difficult to understand the behavior of an object, especially if the code is complex.
  • This may lead to performance issues, as polymorphic behavior may require additional computations at runtime.


Next Article
Article Tags :
Practice Tags :

Similar Reads

three90RightbarBannerImg