In Java, function overloading is called Method Overloading.
Definition: In java method overloading means creating more than one method with same name but with different signature.
i.e., If name of the method remains common but the number and type of parameters are different, then it is called method overloading in Java.
Overloaded Methods:
Here, these methods have same return type and name, but the signature(i.e., the parameter it takes are different).
void sum(int a, int b) { System.out.println("Int: Sum of "+a+" and "+b+" is "+(a+b)); } void sum(float a, float b) { System.out.println("Float: Sum of "+a+" and "+b+" is "+(a+b)); } void sum(String a, String b) { System.out.println(a+" "+b); }
One takes int value, other takes float value and the 3rd takes two string values as parameters.
These parameter type decides which method to call.
Video Tutorial for the working of Method/Funtion overloading in Java
[youtube https://www.youtube.com/watch?v=x7WMSdgMq60]
Full Source Code:(overLoad.java)
import java.lang.*; class work { void sum(int a, int b) { System.out.println("Int: Sum of "+a+" and "+b+" is "+(a+b)); } void sum(float a, float b) { System.out.println("Float: Sum of "+a+" and "+b+" is "+(a+b)); } void sum(String a, String b) { System.out.println(a+" "+b); } } class overLoad { public static void main(String args[]) { work w1 = new work(); w1.sum(10,20); w1.sum(10.5F,1.5F); w1.sum("I Love","You!"); } }
output:
Int: Sum of 10 and 20 is 30
Float: Sum of 10.5 and 1.5 is 12.0
I Love You!