Ad

Java Method Overloading

We can create different methods in one class that may have same name with different arguments. The difference may be in number of arguments or in type of arguments.

Some valid syntax for method overloading

void method1(int);
void method1(int , int);
void method1(float);
void method1(double);
void method2(int, float);
void method2(float, int);
void method3(float, float);
void method3(double, double);
void method3(float, double);
void method3(double, float);

Invalid syntax

void method(float, float);
void method(float, float);
// same argument, same return type: invalid syntax
void method(float, float);
float method(float, float);
// same argument, different return type: invalid syntax

Example: find area of circle and rectangle using method overloading

public class Area {
    public static float area(float r) { //circle
        float a = 3.14F * r* r;
        return a;
    } 
    public static int area(int l, int b) { //rectangle
        int a = l*b;
        return a;
    }
    //find area of square: side * side
    public static void main(String[] args) {
        float a=area(5); //call circle
        int b=area(5, 10); //call rec
        System.out.println("Area of circle = "+ a);
        System.out.println("Area of rec = "+ b);
    }    
}