What is Method Overloading in Java?
Methods are the helping hand of any object in Java. With the help of methods we can describe how an object will behave. Let us first look at methods in java.
Methods in Java
A method is basically a block of code which runs only when it is called. It is also known as functions, as they are used to perform certain specific action. A method can contain one or more parameters, with which you can pass some data into the method. Let us look at an example to understand methods in java.
Example
Output
Let us look at the output of the above example code.
Here in this example code the method newMethod() is created which prints “Hello
there!!” on
the screen. In the main method the newMethod() created is called. Each method must
be
declared inside a class. To declare a method, define the name of the method followed by
parenthesis. To call a method in java, type the name of the method followed by a parenthesis
and a semicolon.
Note: System.out.println() is also a method. It is part of the
pre-defined methods provided in Java.
Method Overloading in Java
Method overloading in Java is one of the unique features of OOPs. It allows different methods to have same name, but with different signatures. The signature can differ in number of input parameters, type of input parameters or both. Let us look at an example to understand method overloading in java.
Example
Output
Let us look at the output of the above example code.
Let us go through the example line by line. In this class method_overloading, we
have
declared our main method first, in which we have called our add() methods with the
help of
an object m of the class method_overloading.
After defining the main method, we move on to the add() methods where we have
two parameters in the first case, both the parameters being int type. Next we have
the add()
method with two parameter, but the parameters are of double type. Finally, there are three
parameters of int type in the last case. Each method returns the sum of the
parameters
passed.
Note: Like any other method we can overload the main() method
too in Java. Method overloading is an example of static or compile time polymorphism.
Summary
In this article, we have seen what a method means in Java along with how to create and call
a method. We have walked through the concept of method overloading and how to implement it.
The redundancy of creating and remembering functions doing the same work is eliminated
with the help of method overloading.