- 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
- Types of Polymorphism: Explore Static and Dynamic Polymorphism in Java With Examples
Types of Polymorphism: Explore Static and Dynamic Polymorphism in Java With Examples
Updated on Feb 28, 2025 | 18 min read
Share:
Table of Contents
- What is Polymorphism in Java? Meaning and Definition With Examples
- What are the Two Main Types of Polymorphism in Java?
- How Does Compile-Time Polymorphism Work? Learn With Examples
- How Does Runtime Polymorphism Work? Learn With Examples
- How Do Static and Dynamic Polymorphism in Java Differ?
- Which Best Practices Help When Using Polymorphism?
- What are the Advantages of Using Polymorphism Types in Java?
- What are the Disadvantages of Using Polymorphism Types in Java?
- How Can upGrad Help You?
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 CreditCardPayment, PayPalPayment, 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 CSVParser, JSONParser, 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 1: super.powerOn() runs the parent’s method first, ensuring the basic setup from Gadget still happens.
- Step 2: Smartphone 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.
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.
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
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?
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