- Blog Categories
- Software Development
- Data Science
- AI/ML
- Marketing
- General
- MBA
- Management
- Legal
- Software Development Projects and Ideas
- 12 Computer Science Project Ideas
- 28 Beginner Software Projects
- Top 10 Engineering Project Ideas
- Top 10 Easy Final Year Projects
- Top 10 Mini Projects for Engineers
- 25 Best Django Project Ideas
- Top 20 MERN Stack Project Ideas
- Top 12 Real Time Projects
- Top 6 Major CSE Projects
- 12 Robotics Projects for All Levels
- Java Programming Concepts
- Abstract Class in Java and Methods
- Constructor Overloading in Java
- StringBuffer vs StringBuilder
- Java Identifiers: Syntax & Examples
- Types of Variables in Java Explained
- Composition in Java: Examples
- Append in Java: Implementation
- Loose Coupling vs Tight Coupling
- Integrity Constraints in DBMS
- Different Types of Operators Explained
- Career and Interview Preparation in IT
- Top 14 IT Courses for Jobs
- Top 20 Highest Paying Languages
- 23 Top CS Interview Q&A
- Best IT Jobs without Coding
- Software Engineer Salary in India
- 44 Agile Methodology Interview Q&A
- 10 Software Engineering Challenges
- Top 15 Tech's Daily Life Impact
- 10 Best Backends for React
- Cloud Computing Reference Models
- Web Development and Security
- Find Installed NPM Version
- Install Specific NPM Package Version
- Make API Calls in Angular
- Install Bootstrap in Angular
- Use Axios in React: Guide
- StrictMode in React: Usage
- 75 Cyber Security Research Topics
- Top 7 Languages for Ethical Hacking
- Top 20 Docker Commands
- Advantages of OOP
- Data Science Projects and Applications
- 42 Python Project Ideas for Beginners
- 13 Data Science Project Ideas
- 13 Data Structure Project Ideas
- 12 Real-World Python Applications
- Python Banking Project
- Data Science Course Eligibility
- Association Rule Mining Overview
- Cluster Analysis in Data Mining
- Classification in Data Mining
- KDD Process in Data Mining
- Data Structures and Algorithms
- Binary Tree Types Explained
- Binary Search Algorithm
- Sorting in Data Structure
- Binary Tree in Data Structure
- Binary Tree vs Binary Search Tree
- Recursion in Data Structure
- Data Structure Search Methods: Explained
- Binary Tree Interview Q&A
- Linear vs Binary Search
- Priority Queue Overview
- Python Programming and Tools
- Top 30 Python Pattern Programs
- List vs Tuple
- Python Free Online Course
- Method Overriding in Python
- Top 21 Python Developer Skills
- Reverse a Number in Python
- Switch Case Functions in Python
- Info Retrieval System Overview
- Reverse a Number in Python
- Real-World Python Applications
- Data Science Careers and Comparisons
- Data Analyst Salary in India
- Data Scientist Salary in India
- Free Excel Certification Course
- Actuary Salary in India
- Data Analyst Interview Guide
- Pandas Interview Guide
- Tableau Filters Explained
- Data Mining Techniques Overview
- Data Analytics Lifecycle Phases
- Data Science Vs Analytics Comparison
- Artificial Intelligence and Machine Learning Projects
- Exciting IoT Project Ideas
- 16 Exciting AI Project Ideas
- 45+ Interesting ML Project Ideas
- Exciting Deep Learning Projects
- 12 Intriguing Linear Regression Projects
- 13 Neural Network Projects
- 5 Exciting Image Processing Projects
- Top 8 Thrilling AWS Projects
- 12 Engaging AI Projects in Python
- NLP Projects for Beginners
- Concepts and Algorithms in AIML
- Basic CNN Architecture Explained
- 6 Types of Regression Models
- Data Preprocessing Steps
- Bagging vs Boosting in ML
- Multinomial Naive Bayes Overview
- Bayesian Network Example
- Bayes Theorem Guide
- Top 10 Dimensionality Reduction Techniques
- Neural Network Step-by-Step Guide
- Technical Guides and Comparisons
- Make a Chatbot in Python
- Compute Square Roots in Python
- Permutation vs Combination
- Image Segmentation Techniques
- Generative AI vs Traditional AI
- AI vs Human Intelligence
- Random Forest vs Decision Tree
- Neural Network Overview
- Perceptron Learning Algorithm
- Selection Sort Algorithm
- Career and Practical Applications in AIML
- AI Salary in India Overview
- Biological Neural Network Basics
- Top 10 AI Challenges
- Production System in AI
- Top 8 Raspberry Pi Alternatives
- Top 8 Open Source Projects
- 14 Raspberry Pi Project Ideas
- 15 MATLAB Project Ideas
- Top 10 Python NLP Libraries
- Naive Bayes Explained
- Digital Marketing Projects and Strategies
- 10 Best Digital Marketing Projects
- 17 Fun Social Media Projects
- Top 6 SEO Project Ideas
- Digital Marketing Case Studies
- Coca-Cola Marketing Strategy
- Nestle Marketing Strategy Analysis
- Zomato Marketing Strategy
- Monetize Instagram Guide
- Become a Successful Instagram Influencer
- 8 Best Lead Generation Techniques
- Digital Marketing Careers and Salaries
- Digital Marketing Salary in India
- Top 10 Highest Paying Marketing Jobs
- Highest Paying Digital Marketing Jobs
- SEO Salary in India
- Content Writer Salary Guide
- Digital Marketing Executive Roles
- Career in Digital Marketing Guide
- Future of Digital Marketing
- MBA in Digital Marketing Overview
- Digital Marketing Techniques and Channels
- 9 Types of Digital Marketing Channels
- Top 10 Benefits of Marketing Branding
- 100 Best YouTube Channel Ideas
- YouTube Earnings in India
- 7 Reasons to Study Digital Marketing
- Top 10 Digital Marketing Objectives
- 10 Best Digital Marketing Blogs
- Top 5 Industries Using Digital Marketing
- Growth of Digital Marketing in India
- Top Career Options in Marketing
- Interview Preparation and Skills
- 73 Google Analytics Interview Q&A
- 56 Social Media Marketing Q&A
- 78 Google AdWords Interview Q&A
- Top 133 SEO Interview Q&A
- 27+ Digital Marketing Q&A
- Digital Marketing Free Course
- Top 9 Skills for PPC Analysts
- Movies with Successful Social Media Campaigns
- Marketing Communication Steps
- Top 10 Reasons to Be an Affiliate Marketer
- Career Options and Paths
- Top 25 Highest Paying Jobs India
- Top 25 Highest Paying Jobs World
- Top 10 Highest Paid Commerce Job
- Career Options After 12th Arts
- Top 7 Commerce Courses Without Maths
- Top 7 Career Options After PCB
- Best Career Options for Commerce
- Career Options After 12th CS
- Top 10 Career Options After 10th
- 8 Best Career Options After BA
- Projects and Academic Pursuits
- 17 Exciting Final Year Projects
- Top 12 Commerce Project Topics
- Top 13 BCA Project Ideas
- Career Options After 12th Science
- Top 15 CS Jobs in India
- 12 Best Career Options After M.Com
- 9 Best Career Options After B.Sc
- 7 Best Career Options After BCA
- 22 Best Career Options After MCA
- 16 Top Career Options After CE
- Courses and Certifications
- 10 Best Job-Oriented Courses
- Best Online Computer Courses
- Top 15 Trending Online Courses
- Top 19 High Salary Certificate Courses
- 21 Best Programming Courses for Jobs
- What is SGPA? Convert to CGPA
- GPA to Percentage Calculator
- Highest Salary Engineering Stream
- 15 Top Career Options After Engineering
- 6 Top Career Options After BBA
- Job Market and Interview Preparation
- Why Should You Be Hired: 5 Answers
- Top 10 Future Career Options
- Top 15 Highest Paid IT Jobs India
- 5 Common Guesstimate Interview Q&A
- Average CEO Salary: Top Paid CEOs
- Career Options in Political Science
- Top 15 Highest Paying Non-IT Jobs
- Cover Letter Examples for Jobs
- Top 5 Highest Paying Freelance Jobs
- Top 10 Highest Paying Companies India
- Career Options and Paths After MBA
- 20 Best Careers After B.Com
- Career Options After MBA Marketing
- Top 14 Careers After MBA In HR
- Top 10 Highest Paying HR Jobs India
- How to Become an Investment Banker
- Career Options After MBA - High Paying
- Scope of MBA in Operations Management
- Best MBA for Working Professionals India
- MBA After BA - Is It Right For You?
- Best Online MBA Courses India
- MBA Project Ideas and Topics
- 11 Exciting MBA HR Project Ideas
- Top 15 MBA Project Ideas
- 18 Exciting MBA Marketing Projects
- MBA Project Ideas: Consumer Behavior
- What is Brand Management?
- What is Holistic Marketing?
- What is Green Marketing?
- Intro to Organizational Behavior Model
- Tech Skills Every MBA Should Learn
- Most Demanding Short Term Courses MBA
- MBA Salary, Resume, and Skills
- MBA Salary in India
- HR Salary in India
- Investment Banker Salary India
- MBA Resume Samples
- Sample SOP for MBA
- Sample SOP for Internship
- 7 Ways MBA Helps Your Career
- Must-have Skills in Sales Career
- 8 Skills MBA Helps You Improve
- Top 20+ SAP FICO Interview Q&A
- MBA Specializations and Comparative Guides
- Why MBA After B.Tech? 5 Reasons
- How to Answer 'Why MBA After Engineering?'
- Why MBA in Finance
- MBA After BSc: 10 Reasons
- Which MBA Specialization to choose?
- Top 10 MBA Specializations
- MBA vs Masters: Which to Choose?
- Benefits of MBA After CA
- 5 Steps to Management Consultant
- 37 Must-Read HR Interview Q&A
- Fundamentals and Theories of Management
- What is Management? Objectives & Functions
- Nature and Scope of Management
- Decision Making in Management
- Management Process: Definition & Functions
- Importance of Management
- What are Motivation Theories?
- Tools of Financial Statement Analysis
- Negotiation Skills: Definition & Benefits
- Career Development in HRM
- Top 20 Must-Have HRM Policies
- Project and Supply Chain Management
- Top 20 Project Management Case Studies
- 10 Innovative Supply Chain Projects
- Latest Management Project Topics
- 10 Project Management Project Ideas
- 6 Types of Supply Chain Models
- Top 10 Advantages of SCM
- Top 10 Supply Chain Books
- What is Project Description?
- Top 10 Project Management Companies
- Best Project Management Courses Online
- Salaries and Career Paths in Management
- Project Manager Salary in India
- Average Product Manager Salary India
- Supply Chain Management Salary India
- Salary After BBA in India
- PGDM Salary in India
- Top 7 Career Options in Management
- CSPO Certification Cost
- Why Choose Product Management?
- Product Management in Pharma
- Product Design in Operations Management
- Industry-Specific Management and Case Studies
- Amazon Business Case Study
- Service Delivery Manager Job
- Product Management Examples
- Product Management in Automobiles
- Product Management in Banking
- Sample SOP for Business Management
- Video Game Design Components
- Top 5 Business Courses India
- Free Management Online Course
- SCM Interview Q&A
- Fundamentals and Types of Law
- Acceptance in Contract Law
- Offer in Contract Law
- 9 Types of Evidence
- Types of Law in India
- Introduction to Contract Law
- Negotiable Instrument Act
- Corporate Tax Basics
- Intellectual Property Law
- Workmen Compensation Explained
- Lawyer vs Advocate Difference
- Law Education and Courses
- LLM Subjects & Syllabus
- Corporate Law Subjects
- LLM Course Duration
- Top 10 Online LLM Courses
- Online LLM Degree
- Step-by-Step Guide to Studying Law
- Top 5 Law Books to Read
- Why Legal Studies?
- Pursuing a Career in Law
- How to Become Lawyer in India
- Career Options and Salaries in Law
- Career Options in Law India
- Corporate Lawyer Salary India
- How To Become a Corporate Lawyer
- Career in Law: Starting, Salary
- Career Opportunities: Corporate Law
- Business Lawyer: Role & Salary Info
- Average Lawyer Salary India
- Top Career Options for Lawyers
- Types of Lawyers in India
- Steps to Become SC Lawyer in India
- Tutorials
- Software Tutorials
- C Tutorials
- Recursion in C: Fibonacci Series
- Checking String Palindromes in C
- Prime Number Program in C
- Implementing Square Root in C
- Matrix Multiplication in C
- Understanding Double Data Type
- Factorial of a Number in C
- Structure of a C Program
- Building a Calculator Program in C
- Compiling C Programs on Linux
- Java Tutorials
- Handling String Input in Java
- Determining Even and Odd Numbers
- Prime Number Checker
- Sorting a String
- User-Defined Exceptions
- Understanding the Thread Life Cycle
- Swapping Two Numbers
- Using Final Classes
- Area of a Triangle
- Skills
- Explore Skills
- Management Skills
- Software Engineering
- JavaScript
- Data Structure
- React.js
- Core Java
- Node.js
- Blockchain
- SQL
- Full stack development
- Devops
- NFT
- BigData
- Cyber Security
- Cloud Computing
- Database Design with MySQL
- Cryptocurrency
- Python
- Digital Marketings
- Advertising
- Influencer Marketing
- Performance Marketing
- Search Engine Marketing
- Email Marketing
- Content Marketing
- Social Media Marketing
- Display Advertising
- Marketing Analytics
- Web Analytics
- Affiliate Marketing
- MBA
- MBA in Finance
- MBA in HR
- MBA in Marketing
- MBA in Business Analytics
- MBA in Operations Management
- MBA in International Business
- MBA in Information Technology
- MBA in Healthcare Management
- MBA In General Management
- MBA in Agriculture
- MBA in Supply Chain Management
- MBA in Entrepreneurship
- MBA in Project Management
- Management Program
- Consumer Behaviour
- Supply Chain Management
- Financial Analytics
- Introduction to Fintech
- Introduction to HR Analytics
- Fundamentals of Communication
- Art of Effective Communication
- Introduction to Research Methodology
- Mastering Sales Technique
- Business Communication
- Fundamentals of Journalism
- Economics Masterclass
- Free Courses
- Home
- Blog
- Software Development
- Example of Polymorphism in Java: Types, Advantages, Pitfalls, and More
Example of Polymorphism in Java: Types, Advantages, Pitfalls, and More
Updated on Feb 13, 2025 | 16 min read
Share:
Table of Contents
- What is Polymorphism in Java? Learn Through Real-life Examples
- What are the Examples of Polymorphism in Java? Two Major Types
- Run Time Polymorphism in Java vs Compile-time Polymorphism
- What are the Advantages of Polymorphism?
- What are the Disadvantages of Polymorphism?
- What are the Uses of Java Polymorphism in Industries? Real-life Use Cases
- How Can upGrad Help You?
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.
- 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.
- 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 Challenges: When 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.
- Full Stack Development Courses: Master the art of building dynamic applications using Java for the back end and React for the front end.
- Job-Ready Full Stack Developer: Become proficient in both front-end and back-end development with a detailed curriculum that includes key technologies like Java, React, and JavaScript.
- Java Object-oriented Programming Free Course: Establish a strong foundation in Java focusing on object-oriented principles, which are crucial for back-end development.
- JavaScript Basics from Scratch: Strengthen your programming skills with JavaScript and explore essential web development concepts to create interactive applications.
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.
Explore our Popular Software Engineering Courses
Master in-demand Software Development skills like coding, system design, DevOps, and agile methodologies to excel in today’s competitive tech industry.
In-Demand Software Development Skills
Stay informed with our widely-read Software Development articles, covering everything from coding techniques to the latest advancements in software engineering.
Read our Popular Articles related to Software
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?
Get Free Consultation
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
Top Resources