- Blog Categories
- 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
- Gini Index for Decision Trees
- 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
- Brand Manager 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
- 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
- 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
- Search Engine Optimization
- 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
Types of Polymorphism in Java [Static & Dynamic Polymorphism with Examples]
Updated on 19 November, 2024
76.67K+ views
• 18 min read
Table of Contents
The term “polymorphism” comes from Greek words meaning “many forms” — and that’s exactly what this concept is about. In Java, polymorphism is a powerful feature of object-oriented programming that allows one method to adapt and perform various tasks based on the object calling it. Polymorphism helps make your code flexible, reusable, and clean. You can have one command, and based on the context, it knows exactly what to do.
Let’s understand using an example - a woman might be a mother, a manager, a friend, or a mentor—all at the same time. She adjusts her role depending on the situation, but she’s still the same person.
Or consider your smartphone. It’s one device, but it can function as a phone, camera, alarm, or music player based on what you need at the moment.
This is similar to how polymorphism works in Java: one method can adapt and act differently depending on the context.
Java supports two types of polymorphism:
- static (or compile-time)
- dynamic (or runtime)
Each types of polymorphism in Java has its own unique way of handling method calls, which we’ll discuss with practical examples. Let’s explore how polymorphism works in Java and why it’s such an important tool for developers!
Check out OOPs concepts and examples.
Types of Polymorphism in Java
When something is “polymorphic,” it means it can take on many forms. In programming, polymorphism lets us treat objects as instances of their parent class instead of their specific class. This allows one interface to do different things. It makes code flexible and easier to work with.
Polymorphism is one of the four main ideas in Object-Oriented Programming (OOP). There are two main types of polymorphism in Java: compile-time (also called static polymorphism) and runtime (also called dynamic polymorphism). Each type handles data and behaviors in its own way. In this section, we’ll look at both types with definitions, examples, and explanations of how polymorphism works in Java.
Compile-time Polymorphism (Static Polymorphism) in Java
Compile-time Polymorphism, also known as Static Polymorphism, is a type of polymorphism in Java resolved at the time of compilation. It allows methods to have the same name but perform different tasks based on parameters. Unlike dynamic polymorphism, which occurs at runtime, compile-time polymorphism is determined by the compiler, making it faster and more efficient since all method calls are resolved during compilation.
Java achieves compile-time polymorphism mainly through method overloading and operator overloading to a limited extent.
Characteristics of Compile-time Polymorphism
Early Binding:
The compiler determines which method to call during the compile phase.
Method Overloading:
Achieved by having multiple methods in the same class with the same name but different parameter lists.
Efficiency:
Reduces runtime errors and allows optimized method calls since the exact method is decided at compile time.
Method Signature:
Each overloaded method must have a unique signature, which includes the number, type, and order of parameters.
How Compile-time Polymorphism Works
1. Method Overloading:
In method overloading, multiple methods can have the same name in a class but must differ in parameter count, parameter type, or parameter order. The Java compiler decides which method to call based on the method signature at compile time.
Example of Method Overloading:
java
class SimpleCalculator {
// Method with two parameters
int add(int a, int b) {
return a + b;
}
// Overloaded method with three parameters
int add(int a, int b, int c) {
return a + b + c;
}
}
public class Demo {
public static void main(String[] args) {
SimpleCalculator obj = new SimpleCalculator();
// Calls the method with two parameters
System.out.println(obj.add(25, 25)); // Output: 50
// Calls the method with three parameters
System.out.println(obj.add(25, 25, 30)); // Output: 80
}
}
Output
50
80
Explanation
- The SimpleCalculator class defines two add methods:
- The first add method takes two integer parameters (int a and int b) and returns their sum.
- The second add method takes three integer parameters (int a, int b, int c) and returns their combined sum.
Method Overloading:
Both methods are named add, but they have different parameter lists, allowing them to coexist in the same class. Java’s compiler can distinguish between these methods based on the number of arguments passed when they are called.
- In the Demo class:
- obj.add(25, 25); calls the add method with two parameters, so it executes the first method, returning 50.
- obj.add(25, 25, 30); calls the add method with three parameters, so it executes the second method, returning 80.
Here, the add method is overloaded with two versions: one that accepts two parameters and another that accepts three parameters. Based on the arguments passed, the compiler determines which method to call.
2. Rules for Method Overloading in Java:
Number of Parameters:
The method signature can differ by the number of parameters. For example, add(int a, int b) and add(int a, int b, int c) differ in the number of arguments.
Type of Parameters:
The method can also differ by parameter types. For example, add(int a, double b) differs from add(double a, double b).
Order of Parameters:
Another way to overload methods is by changing the order of parameters. For instance, display(String text, int number) and display(int number, String text) are considered different signatures.
3. Limitations:
Java does not support operator overloading (except for the + operator, which is used for both numeric addition and string concatenation). This is to maintain simplicity and avoid confusion.
Subtypes of Compile-time Polymorphism
1. Function Overloading (Method Overloading in Java)
Function overloading (or method overloading in Java) allows multiple methods with the same name to coexist in a class, as long as they differ in their parameter list (either by number, type, or order). This enables a single function name to perform different tasks based on the type of input it receives.
Code Example
java
class Printer {
void print(String text) {
System.out.println("Printing String: " + text);
}
void print(int number) {
System.out.println("Printing Integer: " + number);
}
}
public class Demo {
public static void main(String[] args) {
Printer printer = new Printer();
printer.print("Hello World"); // Calls the method with String parameter
printer.print(100); // Calls the method with int parameter
}
}
Explanation:
- The Printer class has two print methods:
- One that accepts a String and prints "Printing String: " followed by the string.
- Another that accepts an int and prints "Printing Integer: " followed by the integer.
- Method Overloading in Action: The print method is overloaded to handle different types of data. When printer.print("Hello World"); is called, the compiler recognizes the String argument and calls the print method that accepts a String. When printer.print(100); is called, it identifies the int argument and calls the print method that accepts an int.
Output:
mathematica
Printing String: Hello World
Printing Integer: 100
2. Operator Overloading (limited in Java)
Operator overloading allows an operator to perform different operations depending on the context. While Java restricts operator overloading for simplicity, it does overload the + operator to perform both addition and string concatenation.
Code Example of + Operator Overloading
java
public class OperatorOverloadingExample {
public static void main(String[] args) {
// Addition operation
int sum = 10 + 20;
System.out.println("Sum: " + sum); // Expected output: Sum: 30
// Concatenation operation
String message = "Hello" + " World";
System.out.println("Message: " + message); // Expected output: Message: Hello World
}
}
Explanation:
- Addition Operation: When the + operator is used with two numbers, it performs an addition, as shown with int sum = 10 + 20;.
- String Concatenation: When the + operator is used with strings, it concatenates them, as with String message = "Hello" + " World";.
The + operator behaves differently based on the types of operands. If both are numeric, it adds them. If either operand is a String, it performs concatenation, demonstrating Java’s limited form of operator overloading.
Output:
30
Hello World
Must Read: Learn Java free!
3. Templates (Generics in Java)
Java does not have templates like C++, but it uses generics to achieve similar functionality. Generics allow classes and methods to operate on various data types without requiring specific implementations for each type, making code more flexible and type-safe.
Code Example of Generics in Java
java
class Box<T> {
private T item;
public void setItem(T item) {
this.item = item;
}
public T getItem() {
return item;
}
}
public class Demo {
public static void main(String[] args) {
Box<Integer> intBox = new Box<>();
intBox.setItem(100);
System.out.println(intBox.getItem()); // Output: 100
Box<String> strBox = new Box<>();
strBox.setItem("Hello Generics");
System.out.println(strBox.getItem()); // Output: Hello Generics
}
}
Explanation:
- The Box<T> class uses a generic type T to store any data type (Integer, String, etc.) in the item variable.
- Flexibility with Generics: By declaring Box<Integer> intBox, we specify that intBox can only hold Integer values. Similarly, Box<String> strBox can only hold String values. This flexibility is similar to templates in C++.
Output:
100
Hello Generics
Key Advantages of Compile-time Polymorphism
- Faster Execution: Since method calls are resolved at compile time, it results in faster code execution.
- Reduced Runtime Errors: Any mismatched method calls are caught during compilation, minimizing runtime errors.
- Code Flexibility: Method overloading provides flexibility by allowing methods to handle different data inputs and scenarios.
Runtime Polymorphism (Dynamic Polymorphism) in Java
Runtime polymorphism, also known as dynamic polymorphism, is resolved during the program’s execution rather than at compile time. This type of polymorphism in Java is achieved through method overriding, allowing subclasses to provide specific implementations for methods already defined in their superclass. The Java Virtual Machine (JVM) determines which method to call at runtime, providing flexibility and enhancing the scalability of Java programs.
Unlike static polymorphism, where the compiler knows which method to execute, in dynamic polymorphism, this decision is made by the JVM during execution. This feature enables Java programs to handle method calls flexibly, adapting to different classes and promoting code reusability.
How Runtime Polymorphism Works
1. Method Overriding
- Method overriding occurs when a subclass has a method with the same name, return type, and parameters as a method in its superclass. This allows the subclass to provide its own specific implementation for that method.
- When an overridden method is called using a superclass reference that points to a subclass object, the subclass’s version of the method is executed. This dynamic binding provides flexibility in handling method calls across different class types.
Example of Method Overriding:
In this example, we demonstrate runtime polymorphism using two classes, Bike and Splendor. Here, Bike is the superclass with a method run, and Splendor is a subclass that overrides the run method. By creating an instance of Splendor and assigning it to a Bike reference, we observe how Java decides which run method to execute at runtime.
java
class Bike {
void run() {
System.out.println("Bike is running");
}
}
class Splendor extends Bike {
@Override
void run() {
System.out.println("Splendor is running safely at 30 km/h");
}
public static void main(String[] args) {
Bike bike = new Splendor(); // Upcasting
bike.run(); // Output: Splendor is running safely at 30 km/h
}
}
Output:
arduino
Splendor is running safely at 30 km/h
Explanation:
- The Bike class has a run method that prints "Bike is running."
- The Splendor class, which extends Bike, overrides the run method to print "Splendor is running safely at 30 km/h."
- In main, we create a Bike reference (bike) and assign it an instance of Splendor. This is called upcasting, where a subclass object is referenced by a superclass reference.
- When bike.run() is called, Java looks at the actual object type (which is Splendor) and executes the run method in Splendor, not Bike.
This demonstrates runtime polymorphism, where the method call is resolved at runtime based on the actual type of the object (Splendor), even though the reference is of type Bike.
2. Understanding Upcasting
- Upcasting refers to the process of treating a subclass object as an instance of its superclass. In Java, this is done by using a superclass reference to refer to a subclass object. Upcasting is essential for achieving runtime polymorphism because it allows the superclass reference to call overridden methods in the subclass.
Example of Upcasting
In this example, we use ABC as the superclass and XYZ as the subclass. The myMethod in ABC is overridden by XYZ, and we use upcasting to assign an XYZ object to an ABC reference. This shows dynamic binding as the myMethod in XYZ is called at runtime.
java
class ABC {
public void myMethod() {
System.out.println("Method in ABC");
}
}
public class XYZ extends ABC {
@Override
public void myMethod() {
System.out.println("Method in XYZ");
}
public static void main(String[] args) {
ABC obj = new XYZ(); // Upcasting
obj.myMethod(); // Output: Method in XYZ
}
}
Output:
mathematica
Method in XYZ
Explanation:
- The ABC class has a method myMethod that prints "Method in ABC."
- The XYZ class, which extends ABC, overrides myMethod to print "Method in XYZ."
- In main, we create a reference obj of type ABC but assign it an XYZ object. This is upcasting, where a superclass reference points to a subclass object.
- When obj.myMethod() is called, Java identifies the actual object type (XYZ) and executes the overridden method in XYZ instead of ABC.
3. Rules for Method Overriding in Java:
- There must be inheritance between classes.
- The method signature (name, number, and type of arguments) must match exactly between the superclass and subclass.
- The overridden method should be marked with @Override (optional but recommended for readability and error-checking).
Subtypes of Runtime Polymorphism
1. Virtual Functions (conceptual in Java)
Java doesn’t directly use the term "virtual functions" as in C++, but the concept is similar. All non-static and non-final methods in Java are "virtual" by default, meaning they can be overridden in subclasses. When a method is called on a superclass reference pointing to a subclass object, Java dynamically selects the overridden method in the subclass at runtime. This is known as dynamic dispatch.
- Example: In the examples above, methods like run and myMethod act as virtual functions since they enable polymorphic behavior through overriding.
Characteristics of Runtime Polymorphism
- Late Binding: The JVM determines the method to execute at runtime, providing flexibility in method selection.
- Supports Inheritance: Runtime polymorphism relies on inheritance, allowing subclasses to customize superclass methods.
- Dynamic Dispatch: The actual method called is based on the object type at runtime, supporting flexible and adaptable code.
Advantages of Runtime Polymorphism
- Code Reusability and Maintenance: Subclasses can use and customize superclass methods, making code reusable and easier to maintain.
- Increased Flexibility: Programs can handle different types of objects through superclass references, allowing flexible interactions.
- Supports Design Patterns: Runtime polymorphism enables design patterns like Strategy and Template Method, promoting robust design and functionality.
Examples of Polymorphism in Java
Polymorphism in Java can be categorized into compile-time polymorphism (method overloading) and runtime polymorphism (method overriding). Below are detailed explanations and examples to illustrate each type, with three examples each for compile-time and runtime polymorphism.
Compile-Time Polymorphism (Method Overloading)
In compile-time polymorphism, method selection occurs at compile time based on the method signature.
Example 1: MathOperations with Overloaded multiply Method
In this example, the MathOperations class has an overloaded multiply method that can handle either two or three integer arguments.
java
class MathOperations {
// Method to multiply two numbers
int multiply(int a, int b) {
return a * b;
}
// Overloaded method to multiply three numbers
int multiply(int a, int b, int c) {
return a * b * c;
}
}
public class Demo {
public static void main(String[] args) {
MathOperations operations = new MathOperations();
// Calls the multiply method with two parameters
System.out.println("Multiplying two numbers: " + operations.multiply(3, 4)); // Output: 12
// Calls the multiply method with three parameters
System.out.println("Multiplying three numbers: " + operations.multiply(2, 3, 4)); // Output: 24
}
}
Explanation:
- The multiply method is overloaded to handle two different cases: multiplying two numbers and multiplying three numbers.
- The compiler determines which method to call based on the number of arguments.
Output:
yaml
Multiplying two numbers: 12
Multiplying three numbers: 24
Example 2: DistanceCalculator with Overloaded distance Method
In this example, the DistanceCalculator class has an overloaded distance method that calculates distance based on different types of input parameters.
java
class DistanceCalculator {
// Method to calculate distance with speed and time (in km/hr and hours)
double distance(double speed, double time) {
return speed * time;
}
// Overloaded method to calculate distance using velocity and time in meters per second
double distance(int velocity, int time) {
return velocity * time;
}
}
public class Demo {
public static void main(String[] args) {
DistanceCalculator calculator = new DistanceCalculator();
// Calls the distance method with double parameters
System.out.println("Distance (km): " + calculator.distance(60.0, 2.5)); // Output: 150.0
// Calls the distance method with int parameters
System.out.println("Distance (m): " + calculator.distance(5, 10)); // Output: 50
}
}
Explanation:
- The distance method is overloaded to handle different data types: double and int.
- The compiler selects the appropriate method based on the parameter types.
Output:
scss
Distance (km): 150.0
Distance (m): 50
Example 3: Overloading calculateArea for Shapes
Here, the ShapeCalculator class overloads the calculateArea method to compute the area of different shapes based on the parameters provided.
java
class ShapeCalculator {
// Method to calculate area of a circle
double calculateArea(double radius) {
return Math.PI * radius * radius;
}
// Overloaded method to calculate area of a rectangle
double calculateArea(double length, double width) {
return length * width;
}
}
public class Demo {
public static void main(String[] args) {
ShapeCalculator calculator = new ShapeCalculator();
// Calls the calculateArea method for a circle
System.out.println("Area of circle: " + calculator.calculateArea(5.0)); // Output: 78.5398
// Calls the calculateArea method for a rectangle
System.out.println("Area of rectangle: " + calculator.calculateArea(5.0, 10.0)); // Output: 50.0
}
}
Explanation:
- The calculateArea method is overloaded to calculate the area of a circle or a rectangle.
- The compiler chooses the correct method based on the number of parameters.
Output:
mathematica
Area of circle: 78.5398
Area of rectangle: 50.0
Check out upGrad’s Degree Counselling page to explore all undergraduate and postgraduate programs.
Runtime Polymorphism (Method Overriding)
In runtime polymorphism, the method to be executed is determined during runtime based on the object type.
Example 1: Employee Payment Calculation
In this example, the Employee class has a calculatePay method that is overridden by the HourlyEmployee and SalariedEmployee subclasses to calculate pay based on different payment structures.
java
class Employee {
double calculatePay() {
return 0;
}
}
class HourlyEmployee extends Employee {
double hoursWorked;
double hourlyRate;
HourlyEmployee(double hoursWorked, double hourlyRate) {
this.hoursWorked = hoursWorked;
this.hourlyRate = hourlyRate;
}
@Override
double calculatePay() {
return hoursWorked * hourlyRate;
}
}
class SalariedEmployee extends Employee {
double monthlySalary;
SalariedEmployee(double monthlySalary) {
this.monthlySalary = monthlySalary;
}
@Override
double calculatePay() {
return monthlySalary;
}
}
public class Demo {
public static void main(String[] args) {
Employee hourly = new HourlyEmployee(40, 120); // 40 hours at ₹120/hour
Employee salaried = new SalariedEmployee(50000); // Monthly salary of ₹50,000
System.out.println("Hourly Employee Pay: ₹" + hourly.calculatePay()); // Output: ₹4800.0
System.out.println("Salaried Employee Pay: ₹" + salaried.calculatePay()); // Output: ₹50000.0
}
}
Explanation:
- The calculatePay method is overridden in the HourlyEmployee and SalariedEmployee subclasses.
- HourlyEmployee calculates pay based on hours worked and hourly rate.
- SalariedEmployee uses a fixed monthly salary.
- At runtime, Java invokes the appropriate calculatePay method based on the object type (HourlyEmployee or SalariedEmployee).
Output:
yaml
Hourly Employee Pay: ₹4800.0
Salaried Employee Pay: ₹50000.0
Example 2: Library Items with Overridden displayInfo Method
In this example, we have a LibraryItem superclass with a displayInfo method. Book and Magazine subclasses override this method to display information specific to each item type.
java
class LibraryItem {
void displayInfo() {
System.out.println("Library item information.");
}
}
class Book extends LibraryItem {
@Override
void displayInfo() {
System.out.println("This is a book.");
}
}
class Magazine extends LibraryItem {
@Override
void displayInfo() {
System.out.println("This is a magazine.");
}
}
public class Demo {
public static void main(String[] args) {
LibraryItem item1 = new Book();
LibraryItem item2 = new Magazine();
item1.displayInfo(); // Output: This is a book.
item2.displayInfo(); // Output: This is a magazine.
}
}
Explanation:
- The displayInfo method is overridden to provide specific details for Book and Magazine.
- Java dynamically determines the appropriate displayInfo method to call at runtime based on the object type.
Output:
csharp
This is a book.
This is a magazine.
Example 3: Shape Perimeters with Overridden perimeter Method
This example includes a Shape superclass with an overridden perimeter method in subclasses Rectangle and Triangle.
java
class Shape {
double perimeter() {
return 0;
}
}
class Rectangle extends Shape {
double length, width;
Rectangle(double length, double width) {
this.length = length;
this.width = width;
}
@Override
double perimeter() {
return 2 * (length + width);
}
}
class Triangle extends Shape {
double a, b, c;
Triangle(double a, double b, double c) {
this.a = a;
this.b = b;
this.c = c;
}
@Override
double perimeter() {
return a + b + c;
}
}
public class Demo {
public static void main(String[] args) {
Shape rectangle = new Rectangle(5, 10);
Shape triangle = new Triangle(3, 4, 5);
System.out.println("Rectangle Perimeter: " + rectangle.perimeter()); // Output: 30.0
System.out.println("Triangle Perimeter: " + triangle.perimeter()); // Output: 12.0
}
}
Explanation:
- The perimeter method is overridden to calculate the perimeter for different shapes (Rectangle and Triangle).
- Java decides which perimeter method to invoke based on the object type.
Output:
mathematica
Rectangle Perimeter: 30.0
Triangle Perimeter: 12.0
Also Read: Polymorphism In OOPS
Advantages of Polymorphism in Java
Polymorphism in Java provides numerous benefits, making code more flexible, reusable, and easier to manage. Here’s a breakdown of key advantages:
Advantage |
Explanation |
Code Reusability |
Reduces redundancy by allowing shared methods across classes, enabling a single method to handle multiple object types. |
Flexibility and Scalability |
Allows objects to operate differently depending on the context, making the code adaptable to future changes. |
Improved Readability |
Streamlines code by using common interfaces, making it clear what methods are intended to do across different objects. |
Dynamic Binding Support |
Enables the correct method to be called at runtime based on the object’s class, making the code versatile and responsive. |
Easier Generic Programming |
Allows objects to be treated as a single type, simplifying the handling of different object types and reducing code complexity. |
Disadvantages of Polymorphism in Java
While polymorphism is powerful, it does have some drawbacks that can impact performance, complexity, and debugging.
Disadvantage |
Explanation |
Increased Complexity |
Understanding polymorphic behavior can be challenging for beginners, especially in larger codebases. |
Potential for Overhead |
Dynamic method dispatch requires extra computation at runtime, which can lead to performance costs. |
Debugging Difficulties |
Polymorphic code can be harder to debug and trace, as the correct method is chosen at runtime, making it less predictable in some cases. |
Java Tutorial: From Beginner to Pro with upGrad
Master Java with upGrad!
Learn core to advanced Java skills in 9 hours and start building dynamic web apps.
Program Highlights
- Level: Beginner to Advanced
- Duration: 9 Hours
- Topics: DOM Manipulation, Asynchronous Programming, ES6+ Features
Why Learn JavaScript?
- Web Essentials: Key language for interactive websites
- Versatile Use: Applicable in frontend, backend, and mobile app development
- High Demand: Among the top programming languages globally
Career Impact in India
- Salary Range: ₹3.4 Lakhs (Entry-Level) to ₹10.1 Lakhs (Mid-Level) per annum
- Top Fields: Web Development, Full Stack Development, Mobile App Development
Why Choose upGrad?
- Hands-On Projects
- Expert Mentors
- Career Support
Ready to master JavaScript? Join upGrad’s Course Today!
Get started with the latest Java tutorials and level up your skills!
Discover Java tutorials to boost your knowledge. Explore the articles below to find the ideal match for your learning journey.
Learn Java Tutorials
Enhance your expertise with our Software Development Free Courses. Explore the programs below to find your perfect fit.
Explore Our Software Development Free Courses
Advance your in-demand software development skills with our top programs. Discover the right course for you below.
In-Demand Software Development Skills
Explore popular articles related to software to enhance your knowledge. Browse the programs below to find your ideal match.
Read our Popular Articles related to Software
Frequently Asked Questions (FAQs)
1. What is the difference between overloading and overriding?
The difference - Overloading allows multiple methods with the same name in a class, each with different parameter lists. It’s a compile-time feature. Overriding occurs when a subclass provides a specific implementation for a method already defined in its superclass. It’s a runtime feature.
2. Can polymorphism be achieved without inheritance?
No, inheritance is necessary for polymorphism. Polymorphism requires a superclass-subclass relationship to allow objects of different subclasses to be treated as instances of their superclass.
3. Why is Java’s operator overloading limited?
Java restricts operator overloading to keep the language simpler and less error-prone. Only the + operator is overloaded for string concatenation, unlike C++ where more operators can be overloaded.
4. How does Java handle polymorphism internally?
Java uses dynamic method dispatch to determine which method to call at runtime based on the actual object type. This allows it to handle overridden methods in subclasses.
5. What are some practical use cases of polymorphism?
Polymorphism is widely used in scenarios like:
- Implementing interfaces and abstract classes.
- Using a single method that works for different object types.
- Enabling flexible design patterns, like Strategy and Template Method.
6. Is polymorphism possible with static methods in Java?
No, polymorphism only works with instance methods. Static methods are bound at compile-time and cannot be overridden, so they do not support runtime polymorphism.
7. How does polymorphism impact performance in Java?
Runtime polymorphism may have a slight performance impact because method calls are resolved at runtime. However, this impact is minimal, and Java’s Just-In-Time (JIT) compiler optimizes these calls.
8. What’s the role of the @Override annotation in polymorphism?
The @Override annotation helps ensure that a method is correctly overriding a superclass method. It improves readability and helps avoid errors, as the compiler checks if the method is truly an override.
9. Can polymorphism work with abstract classes and interfaces?
Yes, polymorphism works well with both abstract classes and interfaces. Abstract classes and interfaces allow subclasses to provide their own implementations, which can be accessed polymorphically.
10. What is the difference between static and dynamic binding?
Static binding occurs at compile time and is used in method overloading and static methods. Dynamic binding occurs at runtime and is used in method overriding, where the JVM decides which method to call based on the object type.
11. How does polymorphism differ from encapsulation?
Polymorphism allows objects to take on multiple forms, typically achieved through inheritance and method overriding. Encapsulation is the concept of wrapping data and methods into a single unit (a class) and restricting access to it to protect the internal state of the object.
RELATED PROGRAMS