Java Method Overloading - The Coding Shala
Home >> Learn Java >> Java Method Overloading
Java Method Overloading
Java class can have more than one method with the same name but different in parameters, known as Method Overloading.
Question: What is the use of method overloading?
Answer: Suppose we want to perform some operation like an addition but addition can be performed between two numbers, three numbers or two floats or more. So instead of using different methods, we use the same name of the method with different parameters. This can increase the readability of the program.
Method overloading can be achieved by changing numbers of arguments or by changing the data types.
Example of Method Overloading in Java
The following example explains Method Overloading:
Point to Remember: In Java, main() is also a method so we can have multiple numbers of main methods but JVM only calls the main(String args) method.
Note: In Method Overloading type promotion will be done automatically. A byte can be promoted to short, int, float, double. The int can be promoted to long. The char can be promoted to int, long and so on.
Example of Method Overloading with TypePromotion in Java
The following example explains type promotion in Method Overloading:
Method Overloading is related to compile-time or static polymorphism.
Note: In java, Methods cannot be overloaded according to the return type.
We cannot overload static methods if they only differ by static keyword and the number of parameters and types of parameters is the same.
Other Posts You May Like