- 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
Method Overloading in Java [With Examples]
Updated on 14 November, 2024
28.88K+ views
• 13 min read
Table of Contents
Java is a versatile language that follows the concepts of Object-Oriented Programming. Many features of object-oriented programming make the code modular, reusable, flexible, and easy to debug. There are many features of Object-oriented programming, such as inheritance, polymorphism, encapsulation, and abstraction.
In this article, we will discuss method overloading in Java which is the type of polymorphism. The article also contains some unique examples to help you get a better understanding.
Check out our free courses to get an edge over the competition.
Polymorphism
Polymorphism means the ability to appear in different forms. It allows the same method to show different behaviors using different methods. There are two types of Polymorphism: Method Overloading and Method Overriding. Method overloading means multiple methods are having the same name but different arguments.
Learn to build applications like Swiggy, Quora, IMDB and more
Method Overriding means the child class can have a method with the same name as the parent class but with a different implementation. We will discuss Method Overloading in more detail in this article. For Method Overriding, you can visit upGrad and get insights.
Check out upGrad’s Java Bootcamp
Method Overloading in Java
Method Overloading in Java is one of the most useful features of an Object-Oriented Language. It allows a class to have multiple methods with the same name. The only difference that these methods have is the different list of parameters that are passed through these methods.
It can be understood in simple terms with a simple example. A class addition has two methods named add(), one method has parameters int a and int b, while the other has three integer parameters, i.e., int a, int b, and int c. Therefore, the add() method is said to be overloaded.
Check out upGrad’s Full Stack Development Bootcamp (JS/MERN)
The method which will be executed will depend upon the number of parameters passed in the method calling statement. To illustrate, add(20,30) will call the add() method having two parameters, and add(10,20,30) will call the add method with three parameters.
For example, a class may include two various “add” methods. One of them accepts two double values, i.e., “add(double a double b),” and another accepts the two integer values with the syntax: “add(int a, int b).” This important method overloading example implies that the computer automatically determines which method to call at run-time depending on the variable types passed to the method.
upGrad’s Exclusive Software and Tech Webinar for you –
SAAS Business – What is So Different?
Different Ways to Overload a Method
Method overloading in Java can be achieved in different ways. As we have understood that it is the list of parameters that differentiate the two methods with the same name in Java. The different ways of method overloading in Java can be achieved by varying parameters list in one of the below way.
Here are some of the different ways of method overloading in Java, along with example of method overloading in Java:
- Number of parameters
- The data type of parameters
- The sequence of Data type of parameters
The Number of Parameters
As it is clear from the name that there will be a different number of parameters in the overloaded methods which will decide which method to execute seeing the method call statement. Below is the method overloading in Java, where the number of parameters varies.
Method1: add(int, int)
Method2: add(int, int, int)
Method calling statement add(20,30) will execute the method1 and Method calling statement add(10,20,30) will execute the method2.
Method Overloading by changing the number of parameters (or arguments):
Multiply() (This method overloading in java example is without parameter)
Multiply(int a, int b) (This overload method multiplies with two parameters)
Multiply(int a, int b, int c) (This overload method multiplies with three parameters)
These three examples change the number of parameters in the Multiply () method. Likewise, you can add more parameters to overload more Multiply() methods in the same class.
The Data Type of Parameters
In this type of method overloading in Java, the two java methods of a class have the same name, and the number of parameters can be the same or different, but the data type of parameters will differ.
Method1: add(int, int)
Method2: add(int, float)
Method3: add(float, float)
In the above methods, the method name is the same, but the data type of the parameters is different. So, method calling statement add(2, 5.5) will execute the method2. Similarly, add(7.5, 10.25) will execute the method3.
Method Overloading by changing the data type of any single or all parameters:
Multiply(int x, int y) (This method overloading in java example has same data type for both the parameters.)
Multiply(int x, float y) (In this overload method, the second parameter has a different data type.)
Multiply(int x, int y, float z) (In this overload method, the third parameter has a different data type.)
-The last two examples of method overloading show different data types of parameters. You can make such combinations to overload a Java method ‘multiply’.
Get Software Engineering degrees from the World’s top Universities. Earn Executive PG Programs, Advanced Certificate Programs, or Masters Programs to fast-track your career.
The Sequence of the Data Type of Parameters
In this type of method overloading in Java, both the method name and the number of parameters is the same, but the difference lies in the sequence of data types of these parameters. Below is the example of overloaded methods:
Method1: add(int, float)
Method2: add(float, int)
Here, calling the statement to add(100, 75.5) will call the method1 to execute, and add(55.25, 150) will execute method2.
Therefore, it is the parameters in the calling statement that decide which overloaded method will be executed.
Read: Method Overloading in Java
Example of method overriding
In the realm of Java programming, method overloading emerges as a powerful tool, empowering you to enhance code flexibility and achieve code reuse by defining multiple methods within the same class that share the same name but possess distinct parameter lists. This construct explains method overloading in java, allows you to tailor method behavior based on the provided arguments, streamlining development and promoting well-structured code.
Delving into the Mechanism:
The magic of method overloading unfolds at compile time, where the appropriate method variant is selected based on the number and types of arguments you provide when calling the method. This compile-time binding ensures that the correct implementation is invoked, ensuring predictable and reliable code execution.
Crafting a Compelling Example – Real TimeExample of method overloading program in Java:
To illustrate the essence of method overloading, consider the following scenario:
Java
class Animal {
void sound() {
System.out.println(“Animal makes a sound”);
}
}
class Dog extends Animal {
@Override
void sound() {
System.out.println(“Dog barks”);
}
void sound(String message) {
System.out.println(“Dog says: ” + message);
}
}
public class Main {
public static void main(String[] args) {
Animal animal = new Dog(); // Upcasting
animal.sound(); // Calls the overridden method in Dog class (no arguments)
Dog dog = new Dog();
dog.sound(); // Calls the overridden method in Dog class (no arguments)
dog.sound(“Hello!”); // Calls the overloaded method with String argument
}
}
In this example, the Dog class extends the Animal class and:
Overrides the sound() method to provide its specific implementation (no arguments).
Overloads the sound() method by adding a new variant that accepts a String argument, allowing more specific behavior.
Advantages of Method Overloading in Java:
Enhanced Readability: Overloading allows using meaningful method names that reflect the operation performed, depending on the argument types and count.
Improved Code Organization: It enables grouping related methods within a class, simplifying code structure and making it easier to manage.
Increased Flexibility: Developers can implement methods that perform similar functions but with different input parameters, offering flexibility in method usage.
Code Reuse: By overloading methods, code duplication is minimized, promoting reuse and making the codebase more maintainable.
Exploring Method Overriding in Java:
An integral complement to method overloading is method overriding, where a subclass provides a specific implementation of a method that is already defined in its superclass. This technique is pivotal for achieving runtime polymorphism and enhancing flexibility in how objects of different classes are treated. For instance, in a scenario where multiple classes inherit from a common superclass, each subclass can override a generic method defined in the superclass to exhibit behavior that’s specific to the subclass.
Example of Method Overriding in Java:
Consider a class Vehicle with a method move(). A subclass Car can override this method to provide a specific implementation, such as System.out.println(“Car drives on the road”);, while a Boat subclass might implement it as System.out.println(“Boat sails on the water”);. This illustrates how method overriding allows subclasses to tailor inherited methods to their specific needs, ensuring that the correct version of a method is called based on the object’s runtime type, not its compile-time type.
Essential Best Practices:
While method overloading offers immense benefits, adhering to key best practices is crucial:
Meaningful Method Names: Opt for descriptive names that elucidate the purpose of each overloaded method, enhancing code readability and maintainability.
Balance over Excess: While overloading promotes flexibility, avoid creating numerous methods with similar functionality. Strive for a balance to prevent code clutter and confusion.
Distinct Parameter Signatures: When designing overloaded methods, carefully consider the types and order of parameters to establish clear and intuitive signatures. This mitigates ambiguity and unexpected behavior.
Comprehensive Documentation: Provide clear and concise documentation for each overloaded method, including details about parameters, return values, and intended use. This aids understanding and reduces potential misuse.
Rigorous Testing: Conduct thorough testing with diverse input values to ensure each overloaded method operates as expected. This guarantees code reliability and robustness.
Why Do We Need Method Overloading in Java?
Now that you have learned the different ways, as well as different method overloading example in Java, let’s take a look at the importance of method overloading in Java.
If the programmer has created a method in Java to perform some action, but later as part of the requirement the programmer wants the same method to act on different parameters, then the coder can simply use the feature of method overloading in Java. This will allow the programmer to create the methods of performing similar functions with the same name so that they do not have to remember the names later.
After understanding what is method overloading in java, the next crucial thing is to know what its need is. Overloading is very useful in Java. It allows you to overload methods as long as the number of parameters (arguments) or type varies for each method. You may want to perform a complex mathematical operation. but occasionally want to do it using two or three numbers. In those cases, function overloading in java proves useful.
If the programmer has created a method in Java to perform some action, but later as part of the requirement the programmer wants the same method to act on different parameters, then the coder can simply use the feature of method overloading in Java. This will allow the programmer to create the methods of performing similar functions with the same name so that they do not have to remember the names later.
In overloading, a class can accept multiple methods with the same name, distinguished by the number and type of arguments passed in the method. A method overloading example can be used to simplify your calls through the method with the minimum possible numbers of arguments whenever all defaults are acceptable. Alternatively, you can also use it when there are multiple ways to identify the same thing, i.e., name (using String data type) and ID (using Long data type).
In the discussed examples, after the overloaded methods achieve initialization, irrespective of the task, it can be done through a common method. Moreover, method overloading affects the methods at the runtime.
When understanding what is method overloading in java, you also need to know what method binding is. Because the method overloading is static polymorphism, the methods are bound in the compilation process.
Methods’ binding occurs at compile time. Hence, many processes like checking or binding are unnecessary during run time.
If you only alter the method’s return, it is not considered method overloading. It leads to ambiguity errors.
Note that the order of arguments, number of arguments, and type of arguments are subsets of the actual method overloading.
Let’s know about the advantages of performing method overloading in Java.
Advantages of Performing Method Overloading in Java
Below are some of the advantages of method overloading in Java:
- It improves the readability of the written code.
- It adds cleanliness to the code written.
- It can be used on constructors also so that we can create different objects by passing different data.
- It gives the programmers the flexibility of calling different methods with similar names.
- Overloaded methods can have different return types.
Method overloading properties in Java
- In function overloading in java, methods are bound in the compilation process known as static binding. The compiler bind method calls the actual method.
- The overloaded methods work quickly because they are bonded during compile time, and no binding or check is needed during runtime.
- Two overloaded methods should have a unique signature.
Below points explain the properties of a method signature in Java
- The numbers of arguments and the type of argument to a method are parts of the method signature.
- The return type of method is not a part of the method signature.
- Order of arguments is also part of the method signature, but they should be of a different type.
Must Read: Career in Java
Rules for Method Overloading in Java
- The first rule is to change the method signature. Method signature refers to the number of arguments, the sequence of parameters, and the data type of parameters.
- If we only change the return type of the method keeping the method name and arguments the same, then this will not be the method overloading but will give rise to a compilation error.
It is also important to note that the name of the method and the overloaded methods should be the same.
Features Of Method Overloading In Java
Mentioned below are some of the top features of method overloading in Java:
- Method overloading is static polymorphism, meaning the methods are bound during compilation.
- One of the common misconceptions is that only changing the return of the method can account for method overloading. However, that is not at all true and can result in ambiguity error.
- The type of arguments, order of arguments as well as number of arguments comprise the actual method overloading.
- Binding of methods is done at compile time, whereas overloading affects the run-time. This means many processes like binding or checking are not required during the run time.
What is Function Overloading In Java?
Function overloading is mainly used to increase the efficiency of a program and reduce the complexities. It does so by involving more segregated functions that can be used to distinguish between each other according to their individual functionalities. Function overloading in Java basically occurs when functions with the same name can have different parameters passed to them. Overloaded functions are related to static polymorphism or compile time. They can further be used to calculate various mathematical or logical operations that is present within the number of assigned variables in the method.
One of the biggest advantages of function overloading is that you no longer need to create methods that have the same thing as work that is done inside a respective function. This not only provides a solution to the problem of conflicting names but also helps to increase the readability of the program.
Important Points about Method Overloading in Java
- Any code written in Java cannot have methods with the same name. If we create 2 methods with the same name in Java, it will throw a compilation error.
- This can be achieved through method overloading. Method overloading allows programmers to write two or more than two methods with the same name, but different parameter lists.
- Method overloading in Java is similar to constructor overloading. The only difference is method overloading occurs for the methods defined in the class while constructor overloading is for the constructor methods of the class.
- In method overloading in Java, the overloaded methods have a different list of parameters. It has nothing to do with the return type of the method. As an example; if two methods are having the same name and same list of parameters, but different return types, then this is not method overloading in Java, but is an invalid case.
Method 1: int Add (float, float)
Method 2: float Add (float, float)
This is the invalid case of method overloading as both the Add() methods have the same name and same list of parameters.
Below is the code that explains the Method Overloading in Java:
Class sum{
private int a;
private int b;
private int c;
private int d;
int public add(int a, int b){
int c;
c=a+b;
return c;
}
int public add(int a, float b){
int c;
c=a+b;
return c;
}
int public add(float a, float b){
int c;
c=a+b;
return c;
}
int public add(float a, int b, int c){
int d;
d=a+b+c;
return d;
}
}
Public static void main (String[]args)
{
// Creating object of the class in main method
sum obj1 = new sum();
sum1=obj1.add(10,20);
sum2=obj1.add(10,55.5);
sum3=obj1.add(110.5,25.5);
sum4=obj1.add(10,20,30);
}
Also Read: Pattern Programs in Java
What is not method overloading in Java?
Till now, we have looked at some of the basic method overloading example in Java, The following examples help you to know what is not considered method overloading in Java.
Example:1
public void multiply(int c, int d)
public void multiply(int m, int n)
Example:2
public void multiply(int a, int b, float c)
public void multiply(int m, int n, float p)
Example:3
public void multiply(int d, float e, int f)
public int multiply(int p, float q, int r)
Conclusion
In this article, the Method Overloading in Java was discussed in detail, explaining its types, rules, and advantages. The topic was explained in-depth with the help of examples. Let us know in the comments if you have any doubt regarding overloading in Java.
If you’re interested to learn more about Java, full-stack software development, check out upGrad & IIIT-B’s PG Diploma in Full-stack Software Development which is designed for working professionals and offers 500+ hours of rigorous training, 9+ projects, and assignments, IIIT-B Alumni status, practical hands-on capstone projects & job assistance with top firms.
Explore Our Software Development Free Courses
Explore our Popular Software Engineering Courses
In-Demand Software Development Skills
Read our Popular Articles related to Software
Frequently Asked Questions (FAQs)
1. What are the contrasts between C++ and Java?
C++ is a platform-specific programming language, whereas Java is a platform-independent language. C++ is a computer language that is mainly used for system programming. Java is a programming language that is extensively used in desktop, web-based, business, and mobile applications. C++ was created to program systems and applications. It was a C programming language extension. Java was initially intended as a printer interpreter, but it was eventually expanded to include network computing capability. It was created with the intention of being simple to use and accessible to a broader audience. Both C++ and Java programming languages are object-oriented programming languages. However, in the C language, a single root hierarchy is not viable, and everything in Java except fundamental types is an object.
2. What are the roles and responsibilities of Java professionals?
As a Java developer, engineer, or other java experts, you'll be responsible for designing, implementing, and maintaining Java applications with high throughput and low latency, which are necessary for mission-critical systems. You'll be expected to provide high availability and performance while also participating in all stages of the development lifecycle. As a Java professional, you'll be responsible for writing well-designed, efficient, and tested code, as well as conducting software analysis, programming, testing, and debugging. As a Java engineer, you will be expected to conduct software testing, analysis, debugging, and programming. Furthermore, you will also be responsible for managing Java and Java EE applications development, ensuring that the designs follow the laid down guidelines and contribute wherever necessary in the different stages of the development lifecycle.
RELATED PROGRAMS