Java method overloading



Method Overloading :

  1. In Java we can define number of methods in a class with the same name.
  2. Defining two or more methods with the same name in a class is called method overloading.
  3. Compile determine which method to execute automatically.
  4. The return type has no effect on the signature of a method.

What is signature of the method ?

  1. The name of a method along with the types and sequence of the parameters is called signature of the method
  2. Signature of the method should be unique.

Signature of the method includes –

  1. No of Parameteres
  2. Different Parameters
  3. Sequence of the parameters

Some Examples of the Method Overloading :

int display(int num1,int num2);

Or

int display(double num1,int num2);

Or

void display(double num1,double num2);

Live Example :

package com.pritesh.programs;

class Rectangle {
    double length;
    double breadth;

    void area(int length, int width) {
        int areaOfRectangle = length * width;
        System.out.println("Area of Rectangle : " + areaOfRectangle);
    }

    void area(double length, double width) {
        double areaOfRectangle = length * width;
        System.out.println("Area of Rectangle : " + areaOfRectangle);
    }

}

class RectangleDemo {
    public static void main(String args[]) {

        Rectangle r1 = new Rectangle();

        r1.area(10, 20);
        r1.area(10.50, 20.50);

    }
}

Explanation :

  1. We have defined 2 methods with same name and different type of parameters.
  2. When both integer parameters are supplied to the method then it will execute method with all integer parameters and if we supply both floating point numbers as parameter then method with floating numbers will be executed.