Blog_Banner_Asset
    Homebreadcumb forward arrow iconBlogbreadcumb forward arrow iconFull Stack Developmentbreadcumb forward arrow iconMethod Overloading in Java [With Examples]

Method Overloading in Java [With Examples]

Last updated:
27th Feb, 2024
Views
Read Time
13 Mins
share image icon
In this article
Chevron in toc
View All
Method Overloading in Java [With Examples]

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.

Explore Our Software Development Free Courses

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.

Ads of upGrad blog
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: 

  1. Number of parameters
  2. The data type of parameters
  3. 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.

Explore our Popular Software Engineering Courses

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.

In-Demand Software Development Skills

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:

  1. Method overloading is static polymorphism, meaning the methods are bound during compilation.
  2. 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. 
  3. The type of arguments, order of arguments as well as number of arguments comprise the actual method overloading.
  4. 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)

Ads of upGrad blog

public int multiply(int p, float q, int r)

Read our Popular Articles related to Software Development

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.

[sc_fs_multi_faq headline-0=”h2″ question-0=”What are the benefits of Java?” answer-0=”Java has a number of features that set it apart from other languages and environments, making it ideal for almost every programming task. To begin with, Java is simple to learn because it was created to be simple to use, making it easier to write, build, debug, and learn than other programming languages. Second, it is object-oriented, allowing you to write modular applications and code that can be reused. Finally, Java is platform-agnostic, which is one of its most major advantages since it can simply shift from one computer system to another, something that other programming languages can’t accomplish. Java has become a language of choice for offering multinational Internet solutions because of its durability, simplicity of use, cross-platform flexibility, and security features.

Profile

Rohan Vats

Blog Author
Software Engineering Manager @ upGrad. Passionate about building large scale web apps with delightful experiences. In pursuit of transforming engineers into leaders.

Frequently Asked Questions (FAQs)

1What 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.

2What 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.

Explore Free Courses

Suggested Tutorials

View All

Suggested Blogs

Top 7 Node js Project Ideas & Topics
31620
Node.JS is a part of the famous MEAN stack used for web development purposes. An open-sourced server environment, Node is written on JavaScript and he
Read More

by Rohan Vats

05 Mar 2024

How to Rename Column Name in SQL
46979
Introduction We are surrounded by Data. We used to store information on paper in enormous file organizers. But eventually, we have come to store it o
Read More

by Rohan Vats

04 Mar 2024

Android Developer Salary in India in 2024 [For Freshers & Experienced]
901362
Wondering what is the range of Android Developer Salary in India? Software engineering is one of the most sought after courses in India. It is a reno
Read More

by Rohan Vats

04 Mar 2024

7 Top Django Projects on Github [For Beginners & Experienced]
52241
One of the best ways to learn a skill is to use it, and what better way to do this than to work on projects? So in this article, we’re sharing t
Read More

by Rohan Vats

04 Mar 2024

Salesforce Developer Salary in India in 2024 [For Freshers & Experienced]
909259
Wondering what is the range of salesforce salary in India? Businesses thrive because of customers. It does not matter whether the operations are B2B
Read More

by Rohan Vats

04 Mar 2024

15 Must-Know Spring MVC Interview Questions
34783
Spring has become one of the most used Java frameworks for the development of web-applications. All the new Java applications are by default using Spr
Read More

by Arjun Mathur

04 Mar 2024

Front End Developer Salary in India in 2023 [For Freshers & Experienced]
902420
Wondering what is the range of front end developer salary in India? Do you know what front end developers do and the salary they earn? Do you know wh
Read More

by Rohan Vats

04 Mar 2024

50 Most Asked Javascript Interview Questions & Answers [2024]
4452
Javascript Interview Question and Answers In this article, we have compiled the most frequently asked JavaScript Interview Questions. These questions
Read More

by Kechit Goyal

26 Feb 2024

OOP Concepts and Examples That Every Programmer Should Know
25126
In this article, we will cover the basic concepts around Object-Oriented Programming and discuss the commonly used terms: Abstraction, Encapsulation,
Read More

by Rohan Vats

26 Feb 2024

Schedule 1:1 free counsellingTalk to Career Expert
icon
footer sticky close icon