Thursday, 13 October 2011

Method and constructor Overloading


Method Overloading

Overloading refers to the use of the same thing for different purpose. Method overloading is logical methods of calling that have the same name, but different number of arguments and different data types.

Method declaration, definition and calling of method done with same method name but different input arguments. call a method in an object, Java matches up the name first and the number and type of parameters to decide which one of the definitions to execute. This process is known as Polymorphism.
Ex,


class OverloadDemo
{
  void test()
  {
    System.out.println("No parameters");
  }

  // Overload test for one integer parameter.
  void test(int a)
  {
    System.out.println("a: " + a);
  }

  // Overload test for two integer parameters.
  void test(int a, int b)
   {
    System.out.println("a and b: " + a + " " + b);
  }

  // overload test for a double parameter
  double test(double a)
  {
    System.out.println("double a: " + a);
    return a*a;
  }
 
}
 
class Overload
 {
    public static void main(String args[]) {
    OverloadDemo ob = new OverloadDemo();
    double result;
     int x=10;
    // call all versions of test()
    ob.test();
    ob.test(10);
    ob.test(10, 20);
    result = ob.test(123.2);
    System.out.println("Result of ob.test(123.2): " + result);
  }
}

Constructor Overloading

Same as the method overloading. It can be possible to overload a constructor , where constructor have different number of arguments.

The constructor call would depend on the arguments that are specified.

No comments:

Post a Comment