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

Example of Polymorphism in Java: Types, Advantages, Pitfalls, and More

By Pavan Vadapalli

Updated on Feb 13, 2025 | 16 min read

Share:

Imagine being able to trigger different behaviors in your program using the exact same command. That’s the essence of polymorphism in Java. The word polymorphism stems from the Greek words poly (many) and morph (forms), and in OOP (object-oriented programming), it allows a single interface — like a method name — to adapt and take on multiple distinct behaviors. 

You’ll see the example of polymorphism in Java in everyday objects, too. For instance, a smartphone can serve as a camera, music player, or calculator, yet it remains the same phone. Much like one person can be both a father and an employee (responding differently depending on whether he’s at home or work), Java objects can wear different hats while still sharing a common blueprint. 

In this blog post, you’ll explore examples of polymorphism in Java, how polymorphism works, and its two main types (compile-time and runtime).

What is Polymorphism in Java? Learn Through Real-life Examples

Polymorphism in Java means using one method name or interface to perform different tasks based on the specific class or object involved. It hinges on Java inheritance and interfaces, which let you group shared features in a parent class (or interface) and override or implement them in child classes. 

Below, you’ll see a sample program demonstrating how one method call can produce different outcomes, all thanks to polymorphism. 

  • In this code, Printer acts as a parent class with a general print() method. 
  • The subclasses PhotoPrinter and DocumentPrinter override that same method to fit their unique printing styles. 
  • In the main method, each variable has the type Printer, yet each line calls a different version of print(), based on which subclass object the variable holds. 

This is the core of polymorphism: you call print(), and Java decides which version to run at runtime, depending on the actual object.

class Printer {
    void print() {
        System.out.println("Standard printing");
    }
}

class PhotoPrinter extends Printer {
    void print() {
        System.out.println("High-resolution photo printing");
    }
}

class DocumentPrinter extends Printer {
    void print() {
        System.out.println("Fast text printing");
    }
}

public class PrintDemo {
    public static void main(String[] args) {
        Printer p1 = new Printer();
        Printer p2 = new PhotoPrinter();
        Printer p3 = new DocumentPrinter();

        p1.print();  // Standard printing
        p2.print();  // High-resolution photo printing
        p3.print();  // Fast text printing
    }
}

Let’s take another real-life example of polymorphism in Java now.

Think of a single pass that covers different modes of transportation. You keep one pass in your wallet, yet you behave differently:

  • Board a city bus by scanning it at the front door
  • Access a local train platform with the same pass
  • Tap it at a metro station gate for quick entry

The pass itself stays the same, but each transport option recognizes it differently. That’s similar to polymorphism in Java, where one reference point can take multiple forms.

Below is a parent class called Pass and child classes for buses, trains, and metros. 

  • Each class has its own way of validating the pass. 
  • You’ll learn how one reference can seamlessly adapt to several specific actions.
class Pass {
    void validate() {
        System.out.println("General pass validation");
    }
}

class BusPass extends Pass {
    void validate() {
        System.out.println("Bus pass validated through onboard scanner");
    }
}

class TrainPass extends Pass {
    void validate() {
        System.out.println("Train pass validated at station counter");
    }
}

class MetroPass extends Pass {
    void validate() {
        System.out.println("Metro pass validated at electronic gate");
    }
}

public class TransportDemo {
    public static void main(String[] args) {
        Pass myPass = new Pass();
        Pass busPass = new BusPass();
        Pass trainPass = new TrainPass();
        Pass metroPass = new MetroPass();

        myPass.validate();
        busPass.validate();
        trainPass.validate();
        metroPass.validate();
    }
}

Here, the validate() call appears the same for every object. However, each subclass (BusPass, TrainPass, and MetroPass) provides its own take on this method. That shows how polymorphism lets you reuse a single reference type while still allowing different behaviors.

For more clarity, check out upGrad’s free tutorial, Pass By Value and Call By Reference in Java.

What are the Examples of Polymorphism in Java? Two Major Types

Polymorphism in Java commonly falls into two groups: compile-time and runtime polymorphism. Both forms revolve around the same core principle – a single interface (or method name) can serve many specialized purposes. 

To understand how this works, it helps to keep a couple of things in mind.

  1. Polymorphic Variables: A parent class reference can point to a child class object, which is what we call a polymorphic variable. Even though the reference looks like the parent, the underlying object still keeps the child’s unique behavior. This lets you write a single piece of code that can flexibly work with different child classes.
  2. Operator Overloading in Java: Java doesn’t let you define custom ways to use operators. The built-in + operator is a special case since it can handle both numeric addition and string concatenation. Apart from that, you won’t find other operator overloading features in Java as you might in some languages like C++.

Moving forward, you’ll see how each type of polymorphism (compile-time and runtime) uses these ideas to provide different methods of achieving “one name, many forms.”

What is Runtime Polymorphism in Java? Implementation With Examples

Runtime polymorphism, sometimes known as dynamic method dispatch, lets the Java Virtual Machine decide which overridden method to call when your code runs. This concept closely relates to what other languages label as virtual functions, where child classes can override a base class method, and the actual method depends on the object type at runtime. 

In Java, non-static instance methods act like virtual functions by default, which means you don’t need extra keywords to make them dynamically dispatched.

Method Overriding and Its Connection to Runtime Polymorphism
Method overriding happens when a child class defines a method with the same name, return type, and parameters as a method in its parent class. Once you store a child object inside a parent reference, Java decides which version of the method to execute based on the child’s actual class. 

That is runtime polymorphism in action: the same method call adapts to whichever overridden version belongs to the real object under the parent reference.

Let’s understand run time polymorphism in Java with examples now.

Example 1: Implementing Runtime Polymorphism in Java

  • A parent class named Animal has a general method called sound().
  • The child class Dog extends Animal and overrides sound() to reflect how a dog barks.
  • Inside the main method, you create an Animal reference but assign a Dog object to it.
  • When you call sound(), Java runs the overridden version in Dog, not the one in Animal.
class Animal {
    void sound() {
        System.out.println("Some generic animal sound");
    }
}

class Dog extends Animal {
    @Override
    void sound() {
        System.out.println("Bark!");
    }
}

public class Example1 {
    public static void main(String[] args) {
        Animal myPet = new Dog();
        myPet.sound();  // Bark!
    }
}

Output: When myPet.sound() runs, the program calls the sound() method from Dog because that class overrides the method in Animal.

Bark!

Example 2: Implementing Runtime Polymorphism in Java

  • You have a class Vehicle with a method called run().
  • Two subclasses, Car and Bike, override the same method.
  • A single Vehicle reference can hold objects of either Car or Bike, so you can call run() and get different outputs depending on which object you assign.
class Vehicle {
    void run() {
        System.out.println("Some generic vehicle is running");
    }
}

class Car extends Vehicle {
    @Override
    void run() {
        System.out.println("Car is running on four wheels");
    }
}

class Bike extends Vehicle {
    @Override
    void run() {
        System.out.println("Bike is running on two wheels");
    }
}

public class Example2 {
    public static void main(String[] args) {
        Vehicle v1 = new Car();
        Vehicle v2 = new Bike();

        v1.run();  // Car is running on four wheels
        v2.run();  // Bike is running on two wheels
    }
}

Output: The run() calls adapt to the correct subclass based on the actual object stored in v1 and v2.

Car is running on four wheels
Bike is running on two wheels

Example 3: Implementing Runtime Polymorphism in Java

  • A class Account includes a method rateOfInterest().
  • Subclasses SavingsAccount and FixedDeposit each override rateOfInterest() to show different interest rates.
  • The reference type remains Account, but the actual object is either SavingsAccount or FixedDeposit.
  • Each object’s method produces a different result when called.
class Account {
    float rateOfInterest() {
        return 0.0f;
    }
}

class SavingsAccount extends Account {
    @Override
    float rateOfInterest() {
        return 4.0f; 
    }
}

class FixedDeposit extends Account {
    @Override
    float rateOfInterest() {
        return 6.5f; 
    }
}

public class Example3 {
    public static void main(String[] args) {
        Account acct1 = new SavingsAccount();
        Account acct2 = new FixedDeposit();

        System.out.println("Savings interest: " + acct1.rateOfInterest() + "%");
        System.out.println("Fixed deposit interest: " + acct2.rateOfInterest() + "%");
    }
}

Output: Because both subclasses override rateOfInterest(), you can maintain a single Account reference type yet still capture each specific behavior at runtime.

Savings interest: 4.0%
Fixed deposit interest: 6.5%

What’s Compile-time Polymorphism in Java? Implementation With Examples

Compile-time polymorphism, sometimes called static binding, lets the Java compiler decide which method to call before the program runs. The language achieves this through method overloading, where multiple methods share the same name but differ by the types or number of parameters. As a result, the compiler picks the right method by analyzing the arguments in each call, and it locks in that choice early.

And as you already know, Java doesn’t allow custom operator overloading, although it does treat the + operator in a special way for numbers and strings. That remains the only built-in operator that handles two roles, performing addition for numbers and concatenation for strings.

Let’s take a look at some examples of compile-time polymorphism in Java.

Example 1: Overloading by Changing the Number of Parameters

  • The class Calculator defines two add() methods.
  • One version accepts two integers.
  • The other accepts three integers.
  • The compiler matches each call with the correct method signature based on the number of parameters you pass.
class Calculator {
    int add(int a, int b) {
        return a + b;
    }

    int add(int a, int b, int c) {
        return a + b + c;
    }
}

public class CompileTimeExample1 {
    public static void main(String[] args) {
        Calculator calc = new Calculator();
        
        // Here, the compiler sees two parameters, so it calls add(int a, int b)
        System.out.println("Result of adding two numbers: " + calc.add(5, 10));
        
        // Here, the compiler sees three parameters, so it calls add(int a, int b, int c)
        System.out.println("Result of adding three numbers: " + calc.add(2, 3, 4));
    }
}

Output: When you use two arguments, you trigger the two-parameter version. With three, the three-parameter version runs. This decision is locked in during compilation.

Result of adding two numbers: 15
Result of adding three numbers: 9

Example 2: Overloading by Changing Parameter Types

  • The class MathOperations has two multiply() methods.
  • One method accepts two integers.
  • Another method accepts two doubles.
  • Both methods share the same name, which would normally create confusion, but the compiler can tell them apart by their parameter types.
class MathOperations {
    int multiply(int x, int y) {
        return x * y;
    }

    double multiply(double x, double y) {
        return x * y;
    }
}

public class CompileTimeExample2 {
    public static void main(String[] args) {
        MathOperations ops = new MathOperations();
        
        // The compiler knows to call multiply(int x, int y)
        System.out.println("Multiplying integers: " + ops.multiply(3, 4));
        
        // The compiler knows to call multiply(double x, double y)
        System.out.println("Multiplying doubles: " + ops.multiply(2.5, 4.0));
    }
}

Output: The compiler resolves each method call ahead of time by matching the argument types with the correct method signature.

Multiplying integers: 12
Multiplying doubles: 10.0

Example 3: Operator Overloading for + (Numbers vs Strings)

  • Java does not allow you to define new operator behaviors but treats the + operator as a built-in overloaded operator.
  • When used with numbers, + performs arithmetic.
  • When used with strings, + joins them.
  • Both actions share the same symbol, yet the compiler determines the right operation based on types.
public class CompileTimeExample3 {
    public static void main(String[] args) {
        
        // When adding integers, the compiler picks numeric addition
        int numResult = 10 + 5;
        System.out.println("Number addition: " + numResult);
        
        // When using strings, the compiler treats + as concatenation
        String textResult = "Hello" + " " + "World";
        System.out.println("String concatenation: " + textResult);
    }
}

Output: The compiler determines that + between integers performs standard addition, while + with strings merges the text. This is an internal language feature that stands out as the only built-in operator overloading in Java.

Number addition: 15
String concatenation: Hello World

Curious to know more about examples of Polymorphism in Java? Start your journey with upGrad’s Core Java course today and gain essential skills!

Run Time Polymorphism in Java vs Compile-time Polymorphism

Both styles of polymorphism handle the idea of giving one name to multiple forms, yet the moment you fix which form to use sets them apart. 

With run time polymorphism, Java decides which method applies while the program is active, based on the actual objects involved. On the other hand, compile-time polymorphism resolves everything before your code starts running. 

Here’s a table that highlights the main differences:

Aspect

Runtime Polymorphism in Java

Compile-time Polymorphism in Java

Alternate Name Dynamic method dispatch Static binding
Key Mechanism Method overriding Method overloading
Decision Time Determined during program execution Determined by the compiler before runtime
Inheritance Need Requires a parent-child relationship Can happen in the same class; no inheritance needed
Speed Often a bit slower (dynamic checks) Generally faster (compiler knows in advance)
Focus Subclasses redefine a parent’s method Methods differ in parameters or argument types
Example Usage Calling a shared method on various subclasses of a base class. Having multiple versions of a method name within one class (e.g., different parameter lists).

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

What are the Advantages of Polymorphism?

Polymorphism in Java lets you shape methods and classes so they adapt to new tasks without endless duplication. This simplifies your work when refining old code to meet fresh demands or unifying multiple actions under one consistent name. It’s a principle that brings order and clarity to projects of all sizes.

Below are some concrete advantages, each highlighting how polymorphism smooths out your coding experience:

  • Code Reusability: You can keep a parent class’s methods and simply override or overload them in different child classes. That approach spares you from rewriting large chunks of code.
  • Reduced Complexity: Having multiple methods with the same name (but different parameters) saves you from introducing countless new names for minor variations of the same operation.
  • Easier Debugging: When a handful of method names handle closely related tasks, you spend less time hunting through scattered functions. It’s simpler to follow the logic and isolate bugs.
  • Support for Design Patterns: Many standard patterns in Java, such as Strategy or Factory, rely on polymorphic behavior. They benefit from the flexibility of overriding and overloading.
  • Increased Flexibility: A parent class reference can hold any subclass object. This makes your code far more dynamic because you can switch between subclasses without altering the main program flow.
  • Consistent Interface: You maintain a uniform set of method names, so it’s easier for you (and anyone on your team) to read and understand the purpose of each call.
  • Better Maintainability: Once your classes and interfaces are defined, extending them with new functionality usually requires changing only the child classes. That keeps the overall structure organized.

Also Read: What are the Advantages of Object-Oriented Programming?

What are the Disadvantages of Polymorphism?

Polymorphism doesn’t always deliver smooth sailing. When it’s taken too far or applied haphazardly, you might encounter deeper layers of confusion and performance slowdowns. Knowing these drawbacks helps you decide when to rely on polymorphism and when to consider simpler solutions.

Below are some typical disadvantages you may face:

  • Performance Overhead: Dynamic method calls involve extra checks during execution. That can slightly slow down your program, especially if you’re dealing with frequent method overrides.
  • Harder to Trace: Overridden methods can make it tough to see which version is actually running. This can lead to extra effort when you need a clear path of execution.
  • Debugging ChallengesWhen the same method name appears in multiple classes, pinpointing why or where a bug appeared can become a lengthy process.
  • Excessive Abstraction: Lengthy inheritance chains, each with its own overrides, can obscure the main logic. You may spend more time piecing together behavior across different classes.
  • Downcasting Issues: Casting a parent reference back to a child class can fail at runtime if the object isn’t really an instance of that child class. This risks unexpected errors.
  • Fragile Base Class Problem: Poorly designed base classes might break child classes when you modify them. A seemingly small change can ripple through the hierarchy.

What are the Uses of Java Polymorphism in Industries? Real-life Use Cases

Polymorphism shows up across many fields, where it supports fresh updates in software without forcing major rewrites. By enabling classes to share a baseline while still tailoring their inner workings, development teams can adapt programs to new requirements more smoothly.

Below is a table that covers several industries and how they put polymorphism into action:

Industries

Example Use Cases

IT & Software Development

- Framework plug-ins implement a common interface yet override methods to integrate seamlessly.

- Microservices share a base contract, while each has unique logic for handling requests.

Banking, Financial Services, Insurance

- Multiple account classes inherit from a single Account type, each overriding methods like calculateInterest().

- Loan objects switch interest formulas based on dynamic criteria.

E-commerce and Retail

- Payment classes (CreditCard, UPI, NetBanking) override a common interface for pay().

- Shipping strategies adapt a shared ShippingMethod parent to handle varied logistics.

Healthcare Patient records rely on a unified structure, with child classes for different specialities overriding methods to format and analyze data.
Gaming

- Characters derived from a base Character class override behavior such as attack() or move().

- Inventory items share one interface but differ in usage and effects.

Automotive A common Vehicle parent leads to Car, Bike, and Truck classes, each with custom run() or fuelUp() methods.
Telecom

- Plans inherit from a single Plan blueprint, overriding data quotas and billing details.

- Service providers implement the same interface but set their own connection parameters.

Manufacturing Machines share an overarching Machine class but override methods for specialized tasks (e.g., drilling, cutting).
Educational Technology Course content inherits from a generic Lesson or Module class, overriding how materials are delivered (video, quiz, or text).
Software Tools Plug-in architectures let each plug-in subclass override the same entry point in an application without major code changes.

How Can upGrad Help You?

With over 1 million+ learners globally enhancing their skills, upGrad has established itself as a leader in programming education. Our programming courses combine industry-relevant curricula, hands-on projects, and mentorship to help you stay ahead in a competitive tech environment. 

Here’s how upGrad supports your programming journey.

Not sure where to begin? upGrad offers personalized career counseling to help you choose the right course.

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 (FAQs)

1. What is an example of polymorphism in Java?

2. Which is a perfect example of runtime polymorphism in Java?

3. Is class an example of polymorphism?

4. Is inheritance an example of polymorphism?

5. Is overriding an example of polymorphism?

6. What is a real life example of polymorphism?

7. What is an example of a polymorphism in software?

8. Is overloading polymorphism?

9. What are the 4 types of polymorphism?

10. What is overloading and overriding?

11. What is an example of overloading and overriding in real time?

Pavan Vadapalli

971 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