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
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: Explore Static and Dynamic Polymorphism in Java With Examples

By Rohan Vats

Updated on Feb 28, 2025 | 18 min read

Share:

You might have noticed that methods in Java can sometimes share the same name but behave differently. This behavior is known as polymorphism, which literally means many forms. Polymorphism is a major concept in object-oriented programming because it lets you write methods once yet get varied outcomes depending on the objects involved.

In this blog, you’ll learn about the two main types of polymorphism — compile-time and runtime — so you can see exactly how Java decides which method to run. Compile-time is also known as static polymorphism, and runtime is dynamic polymorphism in Java.

You’ll also see examples that show how polymorphism keeps your code clear and adaptable. Let’s get started.

What is Polymorphism in Java? Meaning and Definition With Examples

Polymorphism in Java refers to the ability of a single code element — such as a method or an object reference — to perform different tasks based on the context. The term comes from poly (many) and morph (forms), indicating that the same entity can appear or behave in multiple ways. 

It’s a key concept in object-oriented programming that allows you to write methods once and still see varied actions when those methods are applied to different classes or data types. 

Polymorphism makes your Java programs more flexible as you don’t have to reinvent the wheel each time you need similar functionality in slightly different situations. It can also keep your code more organized since you can group related behaviors under one name instead of scattering them across separate methods. 

Below are a few real-world scenarios of Polymorphism to help you understand the concept better before you can explore its two major types:

  • E-Commerce Payments: You could have a Payment class with a processPayment() method. Different subclasses such as CreditCardPaymentPayPalPayment, or BankTransfer would override that method to handle each payment method’s unique details.
  • File Handling: A file-processing system might have a FileParser class with a method called parse(). In subclasses like CSVParserJSONParser, and XMLParser, the same method name is used but each parser processes the file differently.
  • Notification Services: You might have a Notification class and subclasses like EmailNotification or SMSNotification, each with its own version of a send() method. Although both methods share the same name, they behave differently under the hood.

To better understand the topic, you can also check out upGrad's Free Tutorial, Java Classes and Objects

What are the Two Main Types of Polymorphism in Java?

Polymorphism in Java can be grouped into two primary categories. Each type shapes how your methods and classes respond to different inputs or scenarios. If you want your code to be clear, organized, and easier to extend, it’s worth examining both varieties.

1. Compile-Time Polymorphism 

Compile-time polymorphism is also called static polymorphism because the correct method is chosen during compilation. 

It happens when you define multiple methods with the same name but with different parameter lists, such as varying the number or type of arguments. This setup tells the compiler exactly which method to call before your program even runs. 

It can help you avoid cluttering your code with separate method names for similar tasks since you can group related functionality under one common label. By handling method calls early, compile-time polymorphism typically runs faster than its runtime counterpart and helps you catch possible errors in advance.

This polymorphism type in Java can be achieved in the following ways:

  • Method Overloading: Multiple methods with the same name, differing by parameters (type, number, or order).
  • Operator Overloading: Limited in Java (only + for addition and string concatenation).

Did you know? Java also supports compile-time checks through generics, which let you create classes or methods that handle various data types without rewriting the same logic. 

Although generics in Java operate at compile-time, they aren’t typically categorized as a subtype of polymorphism (like overloading). Instead, they belong to the broader notion of parametric polymorphism, where types are bound at compilation to ensure type safety.

2. Runtime Polymorphism

Runtime is also known as dynamic polymorphism in Java. Here, the decision about which method to call is made at runtime based on the actual object type. This occurs when a subclass overrides a method inherited from its parent class. 

While the parent class provides a broad definition, the subclass supplies a more specialized version. When you hold an object through a parent reference but instantiate it as a child type, Java automatically picks the child’s overridden method during execution. 

It helps keep your code extensible, as new child classes can be added without breaking existing code. 

This type of polymorphism can be achieved in the following ways:

  • Method Overriding: A subclass redefines a parent method with the same signature and return type.
  • Virtual Functions: In Java, all non-static and non-final methods behave like virtual functions, enabling dynamic binding.

Why Are Both Types of Polymorphism Important?

Each type solves different challenges and often works hand in hand. Here’s why they’re so important:

  • Flexibility: Compile-time polymorphism streamlines your method naming, while runtime polymorphism adapts to each object’s actual type.
  • Scalability: Overloading catches mismatched calls at compile time, and overriding helps your code evolve as you introduce new subclasses.
  • Code Organization: Both let you group similar operations under common names, reducing clutter.
  • Ease of Maintenance: Overloaded methods keep functionality in one spot, and overridden methods simplify making changes in child classes without rewriting everything else.

Also Read: Difference Between Overloading and Overriding in Java: Understanding the Key Concepts in 2025

How Does Compile-Time Polymorphism Work? Learn With Examples

You’ve already seen that compile-time polymorphism involves selecting the correct method during compilation. What’s new here is how those decisions happen in code. 

By defining multiple methods with the same name or reusing a basic operator differently, you can group related tasks under one umbrella without scattering them across unrelated names.

Example 1: Static Polymorphism Through Method Overloading

Method overloading lets you create more than one method that shares the same name but differs in parameter count, types, or order. This allows you to group related behaviors under a single label while the compiler figures out which version of the method to call before the program runs.

In the example below, we define three methods called multiply, each taking a different set of parameters:

  • multiply(int x, int y) — multiplies two integers.
  • multiply(double x, double y) — multiplies two double values.
  • multiply(int x, int y, int z) — multiplies three integers.

Here’s the code snippet:

public class OverloadDemo {
    // Method to multiply two integers
    public int multiply(int x, int y) {
        return x * y;
    }

    // Method to multiply two doubles
    public double multiply(double x, double y) {
        return x * y;
    }

    // Method to multiply three integers
    public int multiply(int x, int y, int z) {
        return x * y * z;
    }

    public static void main(String[] args) {
        OverloadDemo obj = new OverloadDemo();

        // Calls multiply(int, int)
        System.out.println("Multiplying two integers: " + obj.multiply(3, 4));

        // Calls multiply(double, double)
        System.out.println("Multiplying two doubles: " + obj.multiply(3.5, 2.0));

        // Calls multiply(int, int, int)
        System.out.println("Multiplying three integers: " + obj.multiply(2, 3, 4));
    }
}

Output: 

Multiplying two integers: 12
Multiplying two doubles: 7.0
Multiplying three integers: 24

What’s happening here in the output?

  • The first call (obj.multiply(3, 4)) picks the method with two integer parameters.
  • The second call (obj.multiply(3.5, 2.0)) matches the method with two double parameters.
  • The third call (obj.multiply(2, 3, 4)) routes to the method that accepts three integers.

Example 2: Static Polymorphism Through Operator Overloading

Java doesn’t allow custom operator overloading, but it does treat the + operator differently based on the types of the operands. When you use + with numbers, it performs addition; when you use it with strings, it concatenates them. 

Although limited compared to some languages, this still demonstrates static polymorphism, as the compiler decides how to process + based on the data types you provide.

In the code below, we’ll declare two integer variables, add them using +, and print the result. Then, we’ll take two string variables, join them with +, and print the combined string. The compiler recognizes the type of each operand and decides which version of + to apply.

Here’s the code snippet:

public class OperatorDemo {
    public static void main(String[] args) {
        int a = 5;
        int b = 7;
        int sum = a + b;  // Numeric addition
        System.out.println("Integer addition result: " + sum);

        String word1 = "Hello";
        String word2 = "Java";
        String combined = word1 + " " + word2;  // String concatenation
        System.out.println("String concatenation: " + combined);
    }
}

Output:

Integer addition result: 12
String concatenation: Hello Java

What’s happening here in the output? 

  • a + b is recognized as numeric addition, resulting in 12.
  • word1 + word2 is treated as string concatenation, giving "Hello Java".

How Does Runtime Polymorphism Work? Learn With Examples

While compile-time polymorphism decides which method to call before your code runs, runtime polymorphism, as you know by now, delays that choice until the program is actually in motion. This allows different classes to respond differently to the same method call, even if they share a common parent type.

Let’s understand this better with the help of examples.

Example 1: Dynamic Polymorphism in Java Through Method Overriding

Method overriding happens when a child class redefines a method from its parent class but keeps the same name, parameter list, and return type. This allows each child class to provide a specialized implementation while staying consistent with the parent's interface.

In this example, we’ll define a parent class called Delivery with a method deliverPackage(). Two child classes will override that method to offer unique behaviors:

  • One child class uses drone delivery, meant for lighter packages.
  • Another uses truck delivery, intended for heavier items or longer distances.

Here’s the code snippet:

class Delivery {
    public void deliverPackage() {
        System.out.println("Parent: Delivering a package in a general way.");
    }
}

class DroneDelivery extends Delivery {
    @Override
    public void deliverPackage() {
        System.out.println("DroneDelivery: Flying the package directly to the recipient.");
    }
}

class TruckDelivery extends Delivery {
    @Override
    public void deliverPackage() {
        System.out.println("TruckDelivery: Driving the package across the city.");
    }
}

public class OverridingDemo {
    public static void main(String[] args) {
        Delivery drone = new DroneDelivery();
        Delivery truck = new TruckDelivery();

        drone.deliverPackage();
        truck.deliverPackage();
    }
}

Output:

DroneDelivery: Flying the package directly to the recipient.
TruckDelivery: Driving the package across the city.

What’s happening in the output?

  • drone.deliverPackage() calls the deliverPackage() method defined in DroneDelivery, even though the reference is of type Delivery.
  • truck.deliverPackage() calls the version in TruckDelivery.

Those calls highlight how a single parent reference can trigger different actions depending on the actual subclass.

Example 2: Dynamic Polymorphism in Java Through Dynamic Method Dispatch

Dynamic method dispatch is the process that Java uses to figure out which overridden method to run at runtime. It looks at the real object type, not just the reference type, so the appropriate subclass method is called automatically.

In this example, we’ll define a Payment parent class with a payBill() method. Each child class overrides this method to handle transactions in its own style:

  • A child class processes a card-based payment.
  • Another child processes a cryptocurrency payment.

Here’s the code snippet:

class Payment {
    public void payBill() {
        System.out.println("Payment: Paying the bill in a generic way.");
    }
}

class CardPayment extends Payment {
    @Override
    public void payBill() {
        System.out.println("CardPayment: Processing the bill using a credit/debit card.");
    }
}

class CryptoPayment extends Payment {
    @Override
    public void payBill() {
        System.out.println("CryptoPayment: Using digital currency for the transaction.");
    }
}

public class DispatchDemo {
    public static void main(String[] args) {
        Payment p1 = new CardPayment();
        Payment p2 = new CryptoPayment();

        p1.payBill();
        p2.payBill();
    }
}

Output: 

CardPayment: Processing the bill using a credit/debit card.
CryptoPayment: Using digital currency for the transaction.

What’s happening in the output?

  • p1.payBill() executes the version inside CardPayment, thanks to dynamic dispatch.
  • p2.payBill() triggers the one in CryptoPayment.

This mechanism allows you to build a consistent interface in your parent class while letting each subclass tailor the details to match its purpose.

Example 3: Dynamic Polymorphism in Java Through Virtual Functions

In other languages, a method might be marked as virtual to indicate that subclasses can override it. In Java, all non-static, non-final methods naturally behave this way. The JVM decides at runtime which overridden method to use based on the actual type of the object rather than the reference type. 

This approach is effectively the same mechanism that drives method overriding and dynamic dispatch, but it’s often referred to as virtual functions in discussions about runtime polymorphism.

In this example, we’ll define a Gadget parent class with a powerOn() method. Two subclasses (Smartphone and Laptop) will override powerOn() to provide unique startup routines. Although we’re not labeling any method as virtual, they behave that way behind the scenes.

Here’s the code snippet:

class Gadget {
    public void powerOn() {
        System.out.println("Gadget: Powering on in a general way.");
    }
}

class Smartphone extends Gadget {
    @Override
    public void powerOn() {
        System.out.println("Smartphone: Booting up with a touch screen interface.");
    }
}

class Laptop extends Gadget {
    @Override
    public void powerOn() {
        System.out.println("Laptop: Initializing the operating system.");
    }
}

public class VirtualFunctionDemo {
    public static void main(String[] args) {
        Gadget gadget1 = new Smartphone();
        Gadget gadget2 = new Laptop();

        gadget1.powerOn();
        gadget2.powerOn();
    }
}

Output:

Smartphone: Booting up with a touch screen interface.
Laptop: Initializing the operating system.

What’s happening in the output?

  • Because powerOn() in Gadget is not static or final, it effectively acts as a virtual function.
  • gadget1.powerOn() calls powerOn() from the Smartphone class at runtime, and gadget2.powerOn() calls the version from Laptop.

This is the same mechanism that drives method overriding and dynamic dispatch, just framed through the concept of virtual functions.

upGrad’s Exclusive Software Development Webinar for you –

SAAS Business – What is So Different?

 

Where Does the ‘super’ Keyword Fit In Java Polymorphism?

You might want your child class to keep part of the parent’s original functionality while also adding or modifying it. Java’s super keyword lets you call the parent class’s version of the method within your overridden method. This is particularly helpful if you don't want to entirely replace the parent's logic but extend it.

Let’s understand this with an example. 

In the code below:

  • We’ll start with a parent class named Gadget, which has a method called powerOn().
  • A child class, Smartphone, will override this method but still use super.powerOn() to preserve the parent’s setup steps.
class Gadget {
    public void powerOn() {
        System.out.println("Gadget: Powering on with basic setup.");
    }
}

class Smartphone extends Gadget {
    @Override
    public void powerOn() {
        // Preserve parent logic
        super.powerOn();
        // Add specialized behavior
        System.out.println("Smartphone: Loading mobile operating system.");
    }
}

public class SuperKeywordDemo {
    public static void main(String[] args) {
        Gadget phone = new Smartphone();
        phone.powerOn();
    }
}

Output: 

Gadget: Powering on with basic setup.
Smartphone: Loading mobile operating system.

What’s happening in the output?

  • Step 1super.powerOn() runs the parent’s method first, ensuring the basic setup from Gadget still happens.
  • Step 2Smartphone then adds its own message, indicating a mobile OS is loading.

Also Read: This and Super Keyword in Java

How Do Static and Dynamic Polymorphism in Java Differ?

Polymorphism can appear straightforward on the surface, but static (compile-time) and dynamic (runtime) variations work in very different ways behind the scenes. One resolves the correct method call before your application even starts, while the other waits until your program is running to figure it out. 

Understanding these distinctions will help you pick the right approach for your classes and methods.

Here’s a clear look at the major differences between static and dynamic polymorphism:

Aspect

Compile-Time Polymorphism

Run-Time Polymorphism

Mechanism Typically involves method overloading or limited operator overloading. Achieved through method overriding (child classes redefine methods from the parent class).
Inheritance Not strictly required (you can overload methods within a single class). Requires a parent-child relationship (a subclass must override the parent’s method).
When Decided Chosen by the compiler before the program runs (early binding). Resolved by the Java Virtual Machine during execution (late binding).
Performance Often faster due to early binding and fewer runtime checks. Can be slightly slower because the JVM checks the object’s real type at runtime.
Error Detection Misuse of parameters or missing methods often caught at compile time. Errors can surface later if references don’t match the actual object, though Java’s type system still provides many safeguards.
Flexibility Limited in flexibility, since the signatures must differ in number or type of parameters. More flexible in handling different subclasses through a single parent reference.
Operator Overloading Java only applies this concept to the + operator for numbers vs strings, all determined at compile time. Operator overloading doesn’t apply in the runtime context; overriding deals with methods, not operators.

Which Best Practices Help When Using Polymorphism?

Polymorphism can give your code the flexibility to handle a range of scenarios under a shared structure. However, if you don't manage method overloading and overriding carefully, you can easily end up with confusion.

Here are several guidelines to keep everything consistent:

  • Use @Override Annotation: Mark overridden methods explicitly so you can catch accidental mismatches in names or parameter lists during compilation.
  • Keep Overloading Logical: Overload methods only when they represent variations of the same task, rather than forcing unrelated behaviors under a single name.
  • Limit Deep Inheritance: Avoid extremely long or complicated inheritance chains that make it tough to trace overridden methods. A balanced approach keeps your code easier to follow.
  • Understand Method Resolution: Know that overloading is handled at compile time while overriding is determined at runtime. This helps you predict performance and debug more quickly.
  • Rely on Interfaces or Abstract Classes: If multiple classes share a behavior, define a common interface or an abstract class. Then let each concrete class implement the specific details, staying consistent with the parent contract.
  • Use super Appropriately: When overriding a method, you can still access the parent version with super.methodName(). This preserves original logic if you only need to add or change part of it.

Also Read: Annotations in Java: Types, Uses and Examples

What are the Advantages of Using Polymorphism Types in Java?

Polymorphism in Java can help you avoid cluttering your code with redundant methods and lengthy conditionals. It also provides a more streamlined way to introduce new features without breaking existing functionality.

Below are several reasons why you might find polymorphism beneficial:

  • Code Reusability: By treating objects as instances of their parent class, each child class can customize behavior without forcing you to write entirely new methods.
  • Less Code Duplication: You define one method name for multiple data types or subclass objects, reducing the need to replicate similar logic.
  • Improved Readability: Grouping related tasks under consistent method names makes it easier to understand what each class is supposed to do.
  • Easier Maintenance: You can fix or modify logic in an overridden or overloaded method rather than searching through separate, unconnected method names.
  • Flexible Extensions: Adding new subclasses or new overloaded methods doesn’t break existing code, allowing you to expand features smoothly.
  • Clear Organization: Polymorphism keeps related behaviors in a single place, so you don’t waste time jumping around your codebase.
  • Supports Interface-Based Design: You can create a shared interface or abstract class and let each concrete class implement its own details, all while using a single reference type.
  • Promotes Design Patterns: Many design patterns (like Strategy or Factory) rely on polymorphic behavior to swap out implementations without altering how they’re called.

What are the Disadvantages of Using Polymorphism Types in Java?

Polymorphism can keep your code flexible, but it isn’t a silver bullet. Like any approach in software development, it carries certain drawbacks that you should consider before deciding how many layers of abstraction to include.

Below are some common disadvantages:

  • Potential Runtime Overhead: Dynamic method dispatch can slow execution in performance-critical areas, especially when a program frequently checks object types.
  • Increased Complexity: If you rely on deep inheritance chains or excessive method overrides, it can become confusing to see where a method is actually implemented.
  • Harder to Debug: Tracking down bugs becomes more difficult when multiple classes override the same method, since you have to check several classes to locate the exact implementation.
  • Hidden Behavior: When a subclass overrides a parent method drastically, your code may do something unexpected unless you’re fully aware of the override.
  • Inheritance Pitfalls: Tightly coupled classes or large hierarchies can arise if polymorphism is overused, making your codebase difficult to refactor.
  • Overuse Leads to Confusion: Spreading similar functionality across many overloaded or overridden methods might make the code harder to follow, especially for new contributors.
  • Limited Compile-Time Checks: In some scenarios, polymorphic calls might delay errors until runtime, reducing the safety net that compile-time checking usually provides.

How Can upGrad Help You?

Polymorphism in Java can be your strongest ally when you need code that’s both concise and easy to upgrade. By embracing compile-time polymorphism type, you can organize related methods under one name without overcomplicating your class files. 

When you turn to runtime polymorphism, you gain the freedom to define how objects behave according to their actual types — perfect for scenarios where you want your code to adapt gracefully as new classes join the mix.

If you keep your inheritance hierarchies sensible, use @Override annotations for clarity, and handle the super keyword properly, you’ll avoid much of the confusion that can arise with polymorphism. 

Interested in honing your Java skills further? Consider exploring upGrad’s free certificate course, Core Java Basics. Explore variables, data types, loops, and OOP principles to build strong coding skills with just 23 hours of learning. Book a free career counseling call with our experts or visit your nearest upGrad offline center if you require any career guidance.  

Boost your career with our popular Software Engineering courses, offering hands-on training and expert guidance to turn you into a skilled software developer.

Master in-demand Software Development skills like coding, system design, DevOps, and agile methodologies to excel in today’s competitive tech industry.

Stay informed with our widely-read Software Development articles, covering everything from coding techniques to the latest advancements in software engineering.

Frequently Asked Questions

1. What are the 4 types of polymorphism in Java?

2. What are the different types of inheritance?

3. What is overloading and overriding?

4. Can we override a static method?

5. Why is overriding called runtime polymorphism?

6. Why is Java not pure OOPS?

7. What are two 2 types of method overloading?

8. Can a private method be overridden?

9. Can final methods be overloaded?

10. Why is string immutable in Java?

11. Can final class be inherited?

Rohan Vats

419 articles published

Get Free Consultation

+91

By submitting, I accept the T&C and
Privacy Policy

India’s #1 Tech University

Executive PG Certification in AI-Powered Full Stack Development

77%

seats filled

View Program

Top Resources

Recommended Programs

Suggested Blogs