Function or Method Overloading in Java

Advertisements

Java Function or Method Overloading

More than one function with same name, with different signature in a class or in a same scope is called function overloading. Signature of function includes :

  • Number of arguments
  • Type of arguments
  • Sequence of arguments

When you call an overloaded function, the compiler determines the most appropriate definition to use by comparing the signature of calling statement with the signature specified in the definitions.

Example of java method overloading


	//Calculate.java

    class Calculate
    {

        void Area(int r)                    // function 1
        {
            System.out.print("\n\tArea of Circle    : " + (3.14 * r * r));
        }

        void Area(int l,int b)           // function 2
        {
            System.out.print("\n\tArea of Rectangle : " + (l*b));
        }

        void Area(double l,int b)     // function 3
        {
            System.out.print("\n\tArea of Rectangle : " + (l*b));
        }

        void Area(int l,double b)     // function 4
        {
            System.out.print("\n\tArea of Rectangle : " + (l*b));
        }

        public static void main(String args[])
        {

            Calculate C = new Calculate();

            C.Area(5);                // statement 1
            C.Area(4,6);             // statement 2
            C.Area(9,3.2);          // statement 3
            C.Area(5.1,2);          // statement 4

        }
    }

   Output :

              Area of Circle    : 78.5
              Area of Rectangle : 24
              Area of Rectangle : 28.8
              Area of Rectangle : 10.2

In the above example, we have four member functions named Area.

Statement 1 will invoke function 1 b'coz the signature of function 1 is similar to the statement 1.

Statement 3 will invoke function 4 b'coz statement 3 is passing two arguments, 1st is of integer type and 2nd is of double type. Function 4 is the only function who is receiving integer as 1st argument and double as 2nd argument.

Advertisement