web analytics

Java function overloading

In java we can define multiple methods with same name but different parameters. When we want to perform same operation on data of different data types then function overloading can be used.

Function overloading with different data types

Following examples shows two different function with same name but different data types:

public class Main {
int calculate_square(int num1) {
int square = num1 * num1 ;
System.out.println("Square of given integer: " + square);
}
float calculate_square(float num1) {
float square = num1 * num1 ;
System.out.println("Square of given floating point number: " + square);
}
public static void main(String[] args) {
Main obj = new Main();
// calling overloaded function for an integer
obj.calculate_square(80);
//calling overloading function for a floating point number
obj.calculate_square(53.25);
}
}

Java function overloading with different number of parameters

 

Following example shows two different functions with same name but different number of parameters:


public class Main {
int add(int num1, int num2) {
int sum = num1 + num1 ;
System.out.println("Sum of given numbers: " + sum);
}
int add(int num1, int num2,int num2) {
int sum = num1 + num1 + num2 ;
System.out.println("Sum of given numbers: " + sum);
}
public static void main(String[] args) {
Main obj = new Main();
// calling overloaded function for two parameters
obj.sum(52,63);
//calling overloading function for three parameters
obj.sum(53, 25, 86);
}
}