Explore Courses
Liverpool Business SchoolLiverpool Business SchoolMBA by Liverpool Business School
  • 18 Months
Bestseller
Golden Gate UniversityGolden Gate UniversityMBA (Master of Business Administration)
  • 15 Months
Popular
O.P.Jindal Global UniversityO.P.Jindal Global UniversityMaster of Business Administration (MBA)
  • 12 Months
New
Birla Institute of Management Technology Birla Institute of Management Technology Post Graduate Diploma in Management (BIMTECH)
  • 24 Months
Liverpool John Moores UniversityLiverpool John Moores UniversityMS in Data Science
  • 18 Months
Popular
IIIT BangaloreIIIT BangalorePost Graduate Programme in Data Science & AI (Executive)
  • 12 Months
Bestseller
Golden Gate UniversityGolden Gate UniversityDBA in Emerging Technologies with concentration in Generative AI
  • 3 Years
upGradupGradData Science Bootcamp with AI
  • 6 Months
New
University of MarylandIIIT BangalorePost Graduate Certificate in Data Science & AI (Executive)
  • 8-8.5 Months
upGradupGradData Science Bootcamp with AI
  • 6 months
Popular
upGrad KnowledgeHutupGrad KnowledgeHutData Engineer Bootcamp
  • Self-Paced
upGradupGradCertificate Course in Business Analytics & Consulting in association with PwC India
  • 06 Months
OP Jindal Global UniversityOP Jindal Global UniversityMaster of Design in User Experience Design
  • 12 Months
Popular
WoolfWoolfMaster of Science in Computer Science
  • 18 Months
New
Jindal Global UniversityJindal Global UniversityMaster of Design in User Experience
  • 12 Months
New
Rushford, GenevaRushford Business SchoolDBA Doctorate in Technology (Computer Science)
  • 36 Months
IIIT BangaloreIIIT BangaloreCloud Computing and DevOps Program (Executive)
  • 8 Months
New
upGrad KnowledgeHutupGrad KnowledgeHutAWS Solutions Architect Certification
  • 32 Hours
upGradupGradFull Stack Software Development Bootcamp
  • 6 Months
Popular
upGradupGradUI/UX Bootcamp
  • 3 Months
upGradupGradCloud Computing Bootcamp
  • 7.5 Months
Golden Gate University Golden Gate University Doctor of Business Administration in Digital Leadership
  • 36 Months
New
Jindal Global UniversityJindal Global UniversityMaster of Design in User Experience
  • 12 Months
New
Golden Gate University Golden Gate University Doctor of Business Administration (DBA)
  • 36 Months
Bestseller
Ecole Supérieure de Gestion et Commerce International ParisEcole Supérieure de Gestion et Commerce International ParisDoctorate of Business Administration (DBA)
  • 36 Months
Rushford, GenevaRushford Business SchoolDoctorate of Business Administration (DBA)
  • 36 Months
KnowledgeHut upGradKnowledgeHut upGradSAFe® 6.0 Certified ScrumMaster (SSM) Training
  • Self-Paced
KnowledgeHut upGradKnowledgeHut upGradPMP® certification
  • Self-Paced
IIM KozhikodeIIM KozhikodeProfessional Certification in HR Management and Analytics
  • 6 Months
Bestseller
Duke CEDuke CEPost Graduate Certificate in Product Management
  • 4-8 Months
Bestseller
upGrad KnowledgeHutupGrad KnowledgeHutLeading SAFe® 6.0 Certification
  • 16 Hours
Popular
upGrad KnowledgeHutupGrad KnowledgeHutCertified ScrumMaster®(CSM) Training
  • 16 Hours
Bestseller
PwCupGrad CampusCertification Program in Financial Modelling & Analysis in association with PwC India
  • 4 Months
upGrad KnowledgeHutupGrad KnowledgeHutSAFe® 6.0 POPM Certification
  • 16 Hours
O.P.Jindal Global UniversityO.P.Jindal Global UniversityMaster of Science in Artificial Intelligence and Data Science
  • 12 Months
Bestseller
Liverpool John Moores University Liverpool John Moores University MS in Machine Learning & AI
  • 18 Months
Popular
Golden Gate UniversityGolden Gate UniversityDBA in Emerging Technologies with concentration in Generative AI
  • 3 Years
IIIT BangaloreIIIT BangaloreExecutive Post Graduate Programme in Machine Learning & AI
  • 13 Months
Bestseller
IIITBIIITBExecutive Program in Generative AI for Leaders
  • 4 Months
upGradupGradAdvanced Certificate Program in GenerativeAI
  • 4 Months
New
IIIT BangaloreIIIT BangalorePost Graduate Certificate in Machine Learning & Deep Learning (Executive)
  • 8 Months
Bestseller
Jindal Global UniversityJindal Global UniversityMaster of Design in User Experience
  • 12 Months
New
Liverpool Business SchoolLiverpool Business SchoolMBA with Marketing Concentration
  • 18 Months
Bestseller
Golden Gate UniversityGolden Gate UniversityMBA with Marketing Concentration
  • 15 Months
Popular
MICAMICAAdvanced Certificate in Digital Marketing and Communication
  • 6 Months
Bestseller
MICAMICAAdvanced Certificate in Brand Communication Management
  • 5 Months
Popular
upGradupGradDigital Marketing Accelerator Program
  • 05 Months
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Corporate & Financial Law
  • 12 Months
Bestseller
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in AI and Emerging Technologies (Blended Learning Program)
  • 12 Months
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Intellectual Property & Technology Law
  • 12 Months
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Dispute Resolution
  • 12 Months
upGradupGradContract Law Certificate Program
  • Self paced
New
ESGCI, ParisESGCI, ParisDoctorate of Business Administration (DBA) from ESGCI, Paris
  • 36 Months
Golden Gate University Golden Gate University Doctor of Business Administration From Golden Gate University, San Francisco
  • 36 Months
Rushford Business SchoolRushford Business SchoolDoctor of Business Administration from Rushford Business School, Switzerland)
  • 36 Months
Edgewood CollegeEdgewood CollegeDoctorate of Business Administration from Edgewood College
  • 24 Months
Golden Gate UniversityGolden Gate UniversityDBA in Emerging Technologies with Concentration in Generative AI
  • 36 Months
Golden Gate University Golden Gate University DBA in Digital Leadership from Golden Gate University, San Francisco
  • 36 Months
Liverpool Business SchoolLiverpool Business SchoolMBA by Liverpool Business School
  • 18 Months
Bestseller
Golden Gate UniversityGolden Gate UniversityMBA (Master of Business Administration)
  • 15 Months
Popular
O.P.Jindal Global UniversityO.P.Jindal Global UniversityMaster of Business Administration (MBA)
  • 12 Months
New
Deakin Business School and Institute of Management Technology, GhaziabadDeakin Business School and IMT, GhaziabadMBA (Master of Business Administration)
  • 12 Months
Liverpool John Moores UniversityLiverpool John Moores UniversityMS in Data Science
  • 18 Months
Bestseller
O.P.Jindal Global UniversityO.P.Jindal Global UniversityMaster of Science in Artificial Intelligence and Data Science
  • 12 Months
Bestseller
IIIT BangaloreIIIT BangalorePost Graduate Programme in Data Science (Executive)
  • 12 Months
Bestseller
O.P.Jindal Global UniversityO.P.Jindal Global UniversityO.P.Jindal Global University
  • 12 Months
WoolfWoolfMaster of Science in Computer Science
  • 18 Months
New
Liverpool John Moores University Liverpool John Moores University MS in Machine Learning & AI
  • 18 Months
Popular
Golden Gate UniversityGolden Gate UniversityDBA in Emerging Technologies with concentration in Generative AI
  • 3 Years
Rushford, GenevaRushford Business SchoolDoctorate of Business Administration (AI/ML)
  • 36 Months
Ecole Supérieure de Gestion et Commerce International ParisEcole Supérieure de Gestion et Commerce International ParisDBA Specialisation in AI & ML
  • 36 Months
Golden Gate University Golden Gate University Doctor of Business Administration (DBA)
  • 36 Months
Bestseller
Ecole Supérieure de Gestion et Commerce International ParisEcole Supérieure de Gestion et Commerce International ParisDoctorate of Business Administration (DBA)
  • 36 Months
Rushford, GenevaRushford Business SchoolDoctorate of Business Administration (DBA)
  • 36 Months
Liverpool Business SchoolLiverpool Business SchoolMBA with Marketing Concentration
  • 18 Months
Bestseller
Golden Gate UniversityGolden Gate UniversityMBA with Marketing Concentration
  • 15 Months
Popular
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Corporate & Financial Law
  • 12 Months
Bestseller
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Intellectual Property & Technology Law
  • 12 Months
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Dispute Resolution
  • 12 Months
IIITBIIITBExecutive Program in Generative AI for Leaders
  • 4 Months
New
IIIT BangaloreIIIT BangaloreExecutive Post Graduate Programme in Machine Learning & AI
  • 13 Months
Bestseller
upGradupGradData Science Bootcamp with AI
  • 6 Months
New
upGradupGradAdvanced Certificate Program in GenerativeAI
  • 4 Months
New
KnowledgeHut upGradKnowledgeHut upGradSAFe® 6.0 Certified ScrumMaster (SSM) Training
  • Self-Paced
upGrad KnowledgeHutupGrad KnowledgeHutCertified ScrumMaster®(CSM) Training
  • 16 Hours
upGrad KnowledgeHutupGrad KnowledgeHutLeading SAFe® 6.0 Certification
  • 16 Hours
KnowledgeHut upGradKnowledgeHut upGradPMP® certification
  • Self-Paced
upGrad KnowledgeHutupGrad KnowledgeHutAWS Solutions Architect Certification
  • 32 Hours
upGrad KnowledgeHutupGrad KnowledgeHutAzure Administrator Certification (AZ-104)
  • 24 Hours
KnowledgeHut upGradKnowledgeHut upGradAWS Cloud Practioner Essentials Certification
  • 1 Week
KnowledgeHut upGradKnowledgeHut upGradAzure Data Engineering Training (DP-203)
  • 1 Week
MICAMICAAdvanced Certificate in Digital Marketing and Communication
  • 6 Months
Bestseller
MICAMICAAdvanced Certificate in Brand Communication Management
  • 5 Months
Popular
IIM KozhikodeIIM KozhikodeProfessional Certification in HR Management and Analytics
  • 6 Months
Bestseller
Duke CEDuke CEPost Graduate Certificate in Product Management
  • 4-8 Months
Bestseller
Loyola Institute of Business Administration (LIBA)Loyola Institute of Business Administration (LIBA)Executive PG Programme in Human Resource Management
  • 11 Months
Popular
Goa Institute of ManagementGoa Institute of ManagementExecutive PG Program in Healthcare Management
  • 11 Months
IMT GhaziabadIMT GhaziabadAdvanced General Management Program
  • 11 Months
Golden Gate UniversityGolden Gate UniversityProfessional Certificate in Global Business Management
  • 6-8 Months
upGradupGradContract Law Certificate Program
  • Self paced
New
IU, GermanyIU, GermanyMaster of Business Administration (90 ECTS)
  • 18 Months
Bestseller
IU, GermanyIU, GermanyMaster in International Management (120 ECTS)
  • 24 Months
Popular
IU, GermanyIU, GermanyB.Sc. Computer Science (180 ECTS)
  • 36 Months
Clark UniversityClark UniversityMaster of Business Administration
  • 23 Months
New
Golden Gate UniversityGolden Gate UniversityMaster of Business Administration
  • 20 Months
Clark University, USClark University, USMS in Project Management
  • 20 Months
New
Edgewood CollegeEdgewood CollegeMaster of Business Administration
  • 23 Months
The American Business SchoolThe American Business SchoolMBA with specialization
  • 23 Months
New
Aivancity ParisAivancity ParisMSc Artificial Intelligence Engineering
  • 24 Months
Aivancity ParisAivancity ParisMSc Data Engineering
  • 24 Months
The American Business SchoolThe American Business SchoolMBA with specialization
  • 23 Months
New
Aivancity ParisAivancity ParisMSc Artificial Intelligence Engineering
  • 24 Months
Aivancity ParisAivancity ParisMSc Data Engineering
  • 24 Months
upGradupGradData Science Bootcamp with AI
  • 6 Months
Popular
upGrad KnowledgeHutupGrad KnowledgeHutData Engineer Bootcamp
  • Self-Paced
upGradupGradFull Stack Software Development Bootcamp
  • 6 Months
Bestseller
KnowledgeHut upGradKnowledgeHut upGradBackend Development Bootcamp
  • Self-Paced
upGradupGradUI/UX Bootcamp
  • 3 Months
upGradupGradCloud Computing Bootcamp
  • 7.5 Months
PwCupGrad CampusCertification Program in Financial Modelling & Analysis in association with PwC India
  • 5 Months
upGrad KnowledgeHutupGrad KnowledgeHutSAFe® 6.0 POPM Certification
  • 16 Hours
upGradupGradDigital Marketing Accelerator Program
  • 05 Months
upGradupGradAdvanced Certificate Program in GenerativeAI
  • 4 Months
New
upGradupGradData Science Bootcamp with AI
  • 6 Months
Popular
upGradupGradFull Stack Software Development Bootcamp
  • 6 Months
Bestseller
upGradupGradUI/UX Bootcamp
  • 3 Months
PwCupGrad CampusCertification Program in Financial Modelling & Analysis in association with PwC India
  • 4 Months
upGradupGradCertificate Course in Business Analytics & Consulting in association with PwC India
  • 06 Months
upGradupGradDigital Marketing Accelerator Program
  • 05 Months

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

Updated on 19 November, 2024

76.67K+ views
18 min read

The term “polymorphism” comes from Greek words meaning “many forms” — and that’s exactly what this concept is about. In Java, polymorphism is a powerful feature of object-oriented programming that allows one method to adapt and perform various tasks based on the object calling it. Polymorphism helps make your code flexible, reusable, and clean. You can have one command, and based on the context, it knows exactly what to do. 

Let’s understand using an example - a woman might be a mother, a manager, a friend, or a mentor—all at the same time. She adjusts her role depending on the situation, but she’s still the same person. 

Or consider your smartphone. It’s one device, but it can function as a phone, camera, alarm, or music player based on what you need at the moment. 

This is similar to how polymorphism works in Java: one method can adapt and act differently depending on the context.

Java supports two types of polymorphism: 

  • static (or compile-time) 
  • dynamic (or runtime) 

Each types of polymorphism in Java has its own unique way of handling method calls, which we’ll discuss with practical examples. Let’s explore how polymorphism works in Java and why it’s such an important tool for developers!

Check out OOPs concepts and examples.

Types of Polymorphism in Java

When something is “polymorphic,” it means it can take on many forms. In programming, polymorphism lets us treat objects as instances of their parent class instead of their specific class. This allows one interface to do different things. It makes code flexible and easier to work with.

Polymorphism is one of the four main ideas in Object-Oriented Programming (OOP). There are two main types of polymorphism in Java: compile-time (also called static polymorphism) and runtime (also called dynamic polymorphism). Each type handles data and behaviors in its own way. In this section, we’ll look at both types with definitions, examples, and explanations of how polymorphism works in Java.

Compile-time Polymorphism (Static Polymorphism) in Java

Compile-time Polymorphism, also known as Static Polymorphism, is a type of polymorphism in Java resolved at the time of compilation. It allows methods to have the same name but perform different tasks based on parameters. Unlike dynamic polymorphism, which occurs at runtime, compile-time polymorphism is determined by the compiler, making it faster and more efficient since all method calls are resolved during compilation.

Java achieves compile-time polymorphism mainly through method overloading and operator overloading to a limited extent.

Characteristics of Compile-time Polymorphism

  • Early Binding:

    The compiler determines which method to call during the compile phase.

  • Method Overloading:

    Achieved by having multiple methods in the same class with the same name but different parameter lists.

  • Efficiency:

    Reduces runtime errors and allows optimized method calls since the exact method is decided at compile time.

  • Method Signature:

    Each overloaded method must have a unique signature, which includes the number, type, and order of parameters.

How Compile-time Polymorphism Works

1. Method Overloading:
In method overloading, multiple methods can have the same name in a class but must differ in parameter count, parameter type, or parameter order. The Java compiler decides which method to call based on the method signature at compile time.

Example of Method Overloading:

java

class SimpleCalculator {
    // Method with two parameters
    int add(int a, int b) {
        return a + b;
    }

    // Overloaded method with three parameters
    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();
        
        // Calls the method with two parameters
        System.out.println(obj.add(25, 25));  // Output: 50

        // Calls the method with three parameters
        System.out.println(obj.add(25, 25, 30));  // Output: 80
    }
}

Output

50
80

Explanation

  • The SimpleCalculator class defines two add methods:
    • The first add method takes two integer parameters (int a and int b) and returns their sum.
    • The second add method takes three integer parameters (int aint bint c) and returns their combined sum.
  • Method Overloading:

    Both methods are named add, but they have different parameter lists, allowing them to coexist in the same class. Java’s compiler can distinguish between these methods based on the number of arguments passed when they are called.

  • In the Demo class:
    • obj.add(25, 25); calls the add method with two parameters, so it executes the first method, returning 50.
    • obj.add(25, 25, 30); calls the add method with three parameters, so it executes the second method, returning 80.

Here, the add method is overloaded with two versions: one that accepts two parameters and another that accepts three parameters. Based on the arguments passed, the compiler determines which method to call.

2. Rules for Method Overloading in Java:

  • Number of Parameters:

    The method signature can differ by the number of parameters. For example, add(int a, int b) and add(int a, int b, int c) differ in the number of arguments.

  • Type of Parameters:

    The method can also differ by parameter types. For example, add(int a, double b) differs from add(double a, double b).

  • Order of Parameters:

    Another way to overload methods is by changing the order of parameters. For instance, display(String text, int number) and display(int number, String text) are considered different signatures.

3. Limitations:
Java does not support operator overloading (except for the + operator, which is used for both numeric addition and string concatenation). This is to maintain simplicity and avoid confusion.

 

 

Subtypes of Compile-time Polymorphism

1. Function Overloading (Method Overloading in Java)

Function overloading (or method overloading in Java) allows multiple methods with the same name to coexist in a class, as long as they differ in their parameter list (either by number, type, or order). This enables a single function name to perform different tasks based on the type of input it receives.

Code Example

java

class Printer {
    void print(String text) {
        System.out.println("Printing String: " + text);
    }

    void print(int number) {
        System.out.println("Printing Integer: " + number);
    }
}

public class Demo {
    public static void main(String[] args) {
        Printer printer = new Printer();
        printer.print("Hello World");  // Calls the method with String parameter
        printer.print(100);            // Calls the method with int parameter
    }
}

Explanation:

  • The Printer class has two print methods:
    • One that accepts a String and prints "Printing String: " followed by the string.
    • Another that accepts an int and prints "Printing Integer: " followed by the integer.
  • Method Overloading in Action: The print method is overloaded to handle different types of data. When printer.print("Hello World"); is called, the compiler recognizes the String argument and calls the print method that accepts a String. When printer.print(100); is called, it identifies the int argument and calls the print method that accepts an int.

Output:

mathematica

Printing String: Hello World
Printing Integer: 100

2. Operator Overloading (limited in Java)

Operator overloading allows an operator to perform different operations depending on the context. While Java restricts operator overloading for simplicity, it does overload the + operator to perform both addition and string concatenation.

Code Example of + Operator Overloading

java
public class OperatorOverloadingExample {
    public static void main(String[] args) {
        // Addition operation
        int sum = 10 + 20;
        System.out.println("Sum: " + sum);  // Expected output: Sum: 30

        // Concatenation operation
        String message = "Hello" + " World";
        System.out.println("Message: " + message);  // Expected output: Message: Hello World
    }
}

Explanation:

  • Addition Operation: When the + operator is used with two numbers, it performs an addition, as shown with int sum = 10 + 20;.
  • String Concatenation: When the + operator is used with strings, it concatenates them, as with String message = "Hello" + " World";.

The + operator behaves differently based on the types of operands. If both are numeric, it adds them. If either operand is a String, it performs concatenation, demonstrating Java’s limited form of operator overloading.

Output:

30
Hello World

 

Must Read: Learn Java free!

3. Templates (Generics in Java)

Java does not have templates like C++, but it uses generics to achieve similar functionality. Generics allow classes and methods to operate on various data types without requiring specific implementations for each type, making code more flexible and type-safe.

Code Example of Generics in Java

java

class Box<T> {
    private T item;

    public void setItem(T item) {
        this.item = item;
    }

    public T getItem() {
        return item;
    }
}

public class Demo {
    public static void main(String[] args) {
        Box<Integer> intBox = new Box<>();
        intBox.setItem(100);
        System.out.println(intBox.getItem());  // Output: 100

        Box<String> strBox = new Box<>();
        strBox.setItem("Hello Generics");
        System.out.println(strBox.getItem());  // Output: Hello Generics
    }
}

Explanation:

  • The Box<T> class uses a generic type T to store any data type (IntegerString, etc.) in the item variable.
  • Flexibility with Generics: By declaring Box<Integer> intBox, we specify that intBox can only hold Integer values. Similarly, Box<String> strBox can only hold String values. This flexibility is similar to templates in C++.

Output:

100
Hello Generics

Key Advantages of Compile-time Polymorphism

  • Faster Execution: Since method calls are resolved at compile time, it results in faster code execution.
  • Reduced Runtime Errors: Any mismatched method calls are caught during compilation, minimizing runtime errors.
  • Code Flexibility: Method overloading provides flexibility by allowing methods to handle different data inputs and scenarios.

Runtime Polymorphism (Dynamic Polymorphism) in Java

Runtime polymorphism, also known as dynamic polymorphism, is resolved during the program’s execution rather than at compile time. This type of polymorphism in Java is achieved through method overriding, allowing subclasses to provide specific implementations for methods already defined in their superclass. The Java Virtual Machine (JVM) determines which method to call at runtime, providing flexibility and enhancing the scalability of Java programs.

Unlike static polymorphism, where the compiler knows which method to execute, in dynamic polymorphism, this decision is made by the JVM during execution. This feature enables Java programs to handle method calls flexibly, adapting to different classes and promoting code reusability.

How Runtime Polymorphism Works

1. Method Overriding

  • Method overriding occurs when a subclass has a method with the same name, return type, and parameters as a method in its superclass. This allows the subclass to provide its own specific implementation for that method.
  • When an overridden method is called using a superclass reference that points to a subclass object, the subclass’s version of the method is executed. This dynamic binding provides flexibility in handling method calls across different class types.

Example of Method Overriding:

In this example, we demonstrate runtime polymorphism using two classes, Bike and Splendor. Here, Bike is the superclass with a method run, and Splendor is a subclass that overrides the run method. By creating an instance of Splendor and assigning it to a Bike reference, we observe how Java decides which run method to execute at runtime.

java

class Bike {
    void run() {
        System.out.println("Bike is running");
    }
}

class Splendor extends Bike {
    @Override
    void run() {
        System.out.println("Splendor is running safely at 30 km/h");
    }

    public static void main(String[] args) {
        Bike bike = new Splendor(); // Upcasting
        bike.run();  // Output: Splendor is running safely at 30 km/h
    }
}

Output:

arduino

Splendor is running safely at 30 km/h

Explanation:

  • The Bike class has a run method that prints "Bike is running."
  • The Splendor class, which extends Bike, overrides the run method to print "Splendor is running safely at 30 km/h."
  • In main, we create a Bike reference (bike) and assign it an instance of Splendor. This is called upcasting, where a subclass object is referenced by a superclass reference.
  • When bike.run() is called, Java looks at the actual object type (which is Splendor) and executes the run method in Splendor, not Bike.

This demonstrates runtime polymorphism, where the method call is resolved at runtime based on the actual type of the object (Splendor), even though the reference is of type Bike.

2. Understanding Upcasting

  • Upcasting refers to the process of treating a subclass object as an instance of its superclass. In Java, this is done by using a superclass reference to refer to a subclass object. Upcasting is essential for achieving runtime polymorphism because it allows the superclass reference to call overridden methods in the subclass.

Example of Upcasting

In this example, we use ABC as the superclass and XYZ as the subclass. The myMethod in ABC is overridden by XYZ, and we use upcasting to assign an XYZ object to an ABC reference. This shows dynamic binding as the myMethod in XYZ is called at runtime.

java

class ABC {
    public void myMethod() {
        System.out.println("Method in ABC");
    }
}

public class XYZ extends ABC {
    @Override
    public void myMethod() {
        System.out.println("Method in XYZ");
    }

    public static void main(String[] args) {
        ABC obj = new XYZ();  // Upcasting
        obj.myMethod();  // Output: Method in XYZ
    }
}

Output:

mathematica

Method in XYZ

Explanation:

  • The ABC class has a method myMethod that prints "Method in ABC."
  • The XYZ class, which extends ABC, overrides myMethod to print "Method in XYZ."
  • In main, we create a reference obj of type ABC but assign it an XYZ object. This is upcasting, where a superclass reference points to a subclass object.
  • When obj.myMethod() is called, Java identifies the actual object type (XYZ) and executes the overridden method in XYZ instead of ABC.

3. Rules for Method Overriding in Java:

  • There must be inheritance between classes.
  • The method signature (name, number, and type of arguments) must match exactly between the superclass and subclass.
  • The overridden method should be marked with @Override (optional but recommended for readability and error-checking).

Subtypes of Runtime Polymorphism

1. Virtual Functions (conceptual in Java)

Java doesn’t directly use the term "virtual functions" as in C++, but the concept is similar. All non-static and non-final methods in Java are "virtual" by default, meaning they can be overridden in subclasses. When a method is called on a superclass reference pointing to a subclass object, Java dynamically selects the overridden method in the subclass at runtime. This is known as dynamic dispatch.

  • Example: In the examples above, methods like run and myMethod act as virtual functions since they enable polymorphic behavior through overriding.

Characteristics of Runtime Polymorphism

  • Late Binding: The JVM determines the method to execute at runtime, providing flexibility in method selection.
  • Supports Inheritance: Runtime polymorphism relies on inheritance, allowing subclasses to customize superclass methods.
  • Dynamic Dispatch: The actual method called is based on the object type at runtime, supporting flexible and adaptable code.

Advantages of Runtime Polymorphism

  • Code Reusability and Maintenance: Subclasses can use and customize superclass methods, making code reusable and easier to maintain.
  • Increased Flexibility: Programs can handle different types of objects through superclass references, allowing flexible interactions.
  • Supports Design Patterns: Runtime polymorphism enables design patterns like Strategy and Template Method, promoting robust design and functionality.

Examples of Polymorphism in Java

Polymorphism in Java can be categorized into compile-time polymorphism (method overloading) and runtime polymorphism (method overriding). Below are detailed explanations and examples to illustrate each type, with three examples each for compile-time and runtime polymorphism.

Compile-Time Polymorphism (Method Overloading)

In compile-time polymorphism, method selection occurs at compile time based on the method signature.

  • Example 1: MathOperations with Overloaded multiply Method

In this example, the MathOperations class has an overloaded multiply method that can handle either two or three integer arguments.

java

class MathOperations {
    // Method to multiply two numbers
    int multiply(int a, int b) {
        return a * b;
    }

    // Overloaded method to multiply three numbers
    int multiply(int a, int b, int c) {
        return a * b * c;
    }
}

public class Demo {
    public static void main(String[] args) {
        MathOperations operations = new MathOperations();
        
        // Calls the multiply method with two parameters
        System.out.println("Multiplying two numbers: " + operations.multiply(3, 4));  // Output: 12

        // Calls the multiply method with three parameters
        System.out.println("Multiplying three numbers: " + operations.multiply(2, 3, 4));  // Output: 24
    }
}

Explanation:

  • The multiply method is overloaded to handle two different cases: multiplying two numbers and multiplying three numbers.
  • The compiler determines which method to call based on the number of arguments.

Output:

yaml

Multiplying two numbers: 12
Multiplying three numbers: 24
  • Example 2: DistanceCalculator with Overloaded distance Method

In this example, the DistanceCalculator class has an overloaded distance method that calculates distance based on different types of input parameters.

java

class DistanceCalculator {
    // Method to calculate distance with speed and time (in km/hr and hours)
    double distance(double speed, double time) {
        return speed * time;
    }

    // Overloaded method to calculate distance using velocity and time in meters per second
    double distance(int velocity, int time) {
        return velocity * time;
    }
}

public class Demo {
    public static void main(String[] args) {
        DistanceCalculator calculator = new DistanceCalculator();
        
        // Calls the distance method with double parameters
        System.out.println("Distance (km): " + calculator.distance(60.0, 2.5));  // Output: 150.0

        // Calls the distance method with int parameters
        System.out.println("Distance (m): " + calculator.distance(5, 10));  // Output: 50
    }
}

Explanation:

  • The distance method is overloaded to handle different data types: double and int.
  • The compiler selects the appropriate method based on the parameter types.

Output:

scss

Distance (km): 150.0
Distance (m): 50
  • Example 3: Overloading calculateArea for Shapes

Here, the ShapeCalculator class overloads the calculateArea method to compute the area of different shapes based on the parameters provided.

java

class ShapeCalculator {
    // Method to calculate area of a circle
    double calculateArea(double radius) {
        return Math.PI * radius * radius;
    }

    // Overloaded method to calculate area of a rectangle
    double calculateArea(double length, double width) {
        return length * width;
    }
}

public class Demo {
    public static void main(String[] args) {
        ShapeCalculator calculator = new ShapeCalculator();
        
        // Calls the calculateArea method for a circle
        System.out.println("Area of circle: " + calculator.calculateArea(5.0));  // Output: 78.5398

        // Calls the calculateArea method for a rectangle
        System.out.println("Area of rectangle: " + calculator.calculateArea(5.0, 10.0));  // Output: 50.0
    }
}

Explanation:

  • The calculateArea method is overloaded to calculate the area of a circle or a rectangle.
  • The compiler chooses the correct method based on the number of parameters.

Output:

mathematica

Area of circle: 78.5398
Area of rectangle: 50.0

Check out upGrad’s Degree Counselling page to explore all undergraduate and postgraduate programs.

Runtime Polymorphism (Method Overriding)

In runtime polymorphism, the method to be executed is determined during runtime based on the object type.

  • Example 1: Employee Payment Calculation

In this example, the Employee class has a calculatePay method that is overridden by the HourlyEmployee and SalariedEmployee subclasses to calculate pay based on different payment structures.

java

class Employee {
    double calculatePay() {
        return 0;
    }
}

class HourlyEmployee extends Employee {
    double hoursWorked;
    double hourlyRate;

    HourlyEmployee(double hoursWorked, double hourlyRate) {
        this.hoursWorked = hoursWorked;
        this.hourlyRate = hourlyRate;
    }

    @Override
    double calculatePay() {
        return hoursWorked * hourlyRate;
    }
}

class SalariedEmployee extends Employee {
    double monthlySalary;

    SalariedEmployee(double monthlySalary) {
        this.monthlySalary = monthlySalary;
    }

    @Override
    double calculatePay() {
        return monthlySalary;
    }
}

public class Demo {
    public static void main(String[] args) {
        Employee hourly = new HourlyEmployee(40, 120);  // 40 hours at ₹120/hour
        Employee salaried = new SalariedEmployee(50000);  // Monthly salary of ₹50,000

        System.out.println("Hourly Employee Pay: ₹" + hourly.calculatePay());  // Output: ₹4800.0
        System.out.println("Salaried Employee Pay: ₹" + salaried.calculatePay());  // Output: ₹50000.0
    }
}

Explanation:

  • The calculatePay method is overridden in the HourlyEmployee and SalariedEmployee subclasses.
    • HourlyEmployee calculates pay based on hours worked and hourly rate.
    • SalariedEmployee uses a fixed monthly salary.
  • At runtime, Java invokes the appropriate calculatePay method based on the object type (HourlyEmployee or SalariedEmployee).

Output:

yaml

Hourly Employee Pay: ₹4800.0
Salaried Employee Pay: ₹50000.0
  • Example 2: Library Items with Overridden displayInfo Method

In this example, we have a LibraryItem superclass with a displayInfo method. Book and Magazine subclasses override this method to display information specific to each item type.

java

class LibraryItem {
    void displayInfo() {
        System.out.println("Library item information.");
    }
}

class Book extends LibraryItem {
    @Override
    void displayInfo() {
        System.out.println("This is a book.");
    }
}

class Magazine extends LibraryItem {
    @Override
    void displayInfo() {
        System.out.println("This is a magazine.");
    }
}

public class Demo {
    public static void main(String[] args) {
        LibraryItem item1 = new Book();
        LibraryItem item2 = new Magazine();

        item1.displayInfo();  // Output: This is a book.
        item2.displayInfo();  // Output: This is a magazine.
    }
}

Explanation:

  • The displayInfo method is overridden to provide specific details for Book and Magazine.
  • Java dynamically determines the appropriate displayInfo method to call at runtime based on the object type.

Output:

csharp

This is a book.
This is a magazine.
  • Example 3: Shape Perimeters with Overridden perimeter Method

This example includes a Shape superclass with an overridden perimeter method in subclasses Rectangle and Triangle.

java

class Shape {
    double perimeter() {
        return 0;
    }
}

class Rectangle extends Shape {
    double length, width;

    Rectangle(double length, double width) {
        this.length = length;
        this.width = width;
    }

    @Override
    double perimeter() {
        return 2 * (length + width);
    }
}

class Triangle extends Shape {
    double a, b, c;

    Triangle(double a, double b, double c) {
        this.a = a;
        this.b = b;
        this.c = c;
    }

    @Override
    double perimeter() {
        return a + b + c;
    }
}

public class Demo {
    public static void main(String[] args) {
        Shape rectangle = new Rectangle(5, 10);
        Shape triangle = new Triangle(3, 4, 5);

        System.out.println("Rectangle Perimeter: " + rectangle.perimeter());  // Output: 30.0
        System.out.println("Triangle Perimeter: " + triangle.perimeter());    // Output: 12.0
    }
}

Explanation:

  • The perimeter method is overridden to calculate the perimeter for different shapes (Rectangle and Triangle).
  • Java decides which perimeter method to invoke based on the object type.

Output:

mathematica

Rectangle Perimeter: 30.0
Triangle Perimeter: 12.0

Also Read: Polymorphism In OOPS

Advantages of Polymorphism in Java

Polymorphism in Java provides numerous benefits, making code more flexible, reusable, and easier to manage. Here’s a breakdown of key advantages:

Advantage

Explanation

Code Reusability

Reduces redundancy by allowing shared methods across classes, enabling a single method to handle multiple object types.

Flexibility and Scalability

Allows objects to operate differently depending on the context, making the code adaptable to future changes.

Improved Readability

Streamlines code by using common interfaces, making it clear what methods are intended to do across different objects.

Dynamic Binding Support

Enables the correct method to be called at runtime based on the object’s class, making the code versatile and responsive.

Easier Generic Programming

Allows objects to be treated as a single type, simplifying the handling of different object types and reducing code complexity.

Disadvantages of Polymorphism in Java

While polymorphism is powerful, it does have some drawbacks that can impact performance, complexity, and debugging.

Disadvantage

Explanation

Increased Complexity

Understanding polymorphic behavior can be challenging for beginners, especially in larger codebases.

Potential for Overhead

Dynamic method dispatch requires extra computation at runtime, which can lead to performance costs.

Debugging Difficulties

Polymorphic code can be harder to debug and trace, as the correct method is chosen at runtime, making it less predictable in some cases.

Java Tutorial: From Beginner to Pro with upGrad

Master Java with upGrad!
Learn core to advanced Java skills in 9 hours and start building dynamic web apps.

Program Highlights

  • Level: Beginner to Advanced
  • Duration: 9 Hours
  • Topics: DOM Manipulation, Asynchronous Programming, ES6+ Features

Why Learn JavaScript?

  • Web Essentials: Key language for interactive websites
  • Versatile Use: Applicable in frontend, backend, and mobile app development
  • High Demand: Among the top programming languages globally

Career Impact in India

Why Choose upGrad?

  • Hands-On Projects
  • Expert Mentors
  • Career Support

Ready to master JavaScript? Join upGrad’s Course Today!

Get started with the latest Java tutorials and level up your skills!

Discover Java tutorials to boost your knowledge. Explore the articles below to find the ideal match for your learning journey.

Enhance your expertise with our Software Development Free Courses. Explore the programs below to find your perfect fit.

Advance your in-demand software development skills with our top programs. Discover the right course for you below.

Explore popular articles related to software to enhance your knowledge. Browse the programs below to find your ideal match.

Frequently Asked Questions (FAQs)

1. What is the difference between overloading and overriding?

The difference - Overloading allows multiple methods with the same name in a class, each with different parameter lists. It’s a compile-time feature. Overriding occurs when a subclass provides a specific implementation for a method already defined in its superclass. It’s a runtime feature.

2. Can polymorphism be achieved without inheritance?

No, inheritance is necessary for polymorphism. Polymorphism requires a superclass-subclass relationship to allow objects of different subclasses to be treated as instances of their superclass.

3. Why is Java’s operator overloading limited?

Java restricts operator overloading to keep the language simpler and less error-prone. Only the + operator is overloaded for string concatenation, unlike C++ where more operators can be overloaded.

4. How does Java handle polymorphism internally?

Java uses dynamic method dispatch to determine which method to call at runtime based on the actual object type. This allows it to handle overridden methods in subclasses.

5. What are some practical use cases of polymorphism?

Polymorphism is widely used in scenarios like:

  • Implementing interfaces and abstract classes.
  • Using a single method that works for different object types.
  • Enabling flexible design patterns, like Strategy and Template Method.

6. Is polymorphism possible with static methods in Java?

No, polymorphism only works with instance methods. Static methods are bound at compile-time and cannot be overridden, so they do not support runtime polymorphism.

7. How does polymorphism impact performance in Java?

Runtime polymorphism may have a slight performance impact because method calls are resolved at runtime. However, this impact is minimal, and Java’s Just-In-Time (JIT) compiler optimizes these calls.

8. What’s the role of the @Override annotation in polymorphism?

The @Override annotation helps ensure that a method is correctly overriding a superclass method. It improves readability and helps avoid errors, as the compiler checks if the method is truly an override.

9. Can polymorphism work with abstract classes and interfaces?

Yes, polymorphism works well with both abstract classes and interfaces. Abstract classes and interfaces allow subclasses to provide their own implementations, which can be accessed polymorphically.

10. What is the difference between static and dynamic binding?

Static binding occurs at compile time and is used in method overloading and static methods. Dynamic binding occurs at runtime and is used in method overriding, where the JVM decides which method to call based on the object type.

11. How does polymorphism differ from encapsulation?

Polymorphism allows objects to take on multiple forms, typically achieved through inheritance and method overriding. Encapsulation is the concept of wrapping data and methods into a single unit (a class) and restricting access to it to protect the internal state of the object.

RELATED PROGRAMS