Saturday, September 1, 2012

METHOD OVERLOADING

In same class, if name of the method remains common but the number and type of parameters are different, then it is called method overloading.

Example:


void sum(int a, int b)
 {
  System.out.println("Int: Sum of "+a+" and "+b+" is "+(a+b));
 }
 
 void sum(float a, float b)
 {
  System.out.println("Float: Sum of "+a+" and "+b+" is "+(a+b));
 }
 
 void sum(String a, String b)
 {
  System.out.println(a+" "+b);
 }

One takes int value, other takes float value and the 3rd takes two string values as parameters.


Another Example:
class overLoading
{
   public static void main(String[] args)

  {
   functionOverload obj = new functionOverload();

   obj.add(1,2);
   obj.add(\"Life at \", \"?\");
   obj.add(11.5, 22.5);

   }
}

class functionOverload
 {
   /*  void add(int a, int b)             // 1 - A method with two parameters
     {

        int sum = a + b;
        System.out.println(\"Sum of a+b is \"+sum);

     }    */

     void add(int a, int b, int c)       {

        int sum = a + b + c;
        System.out.println(\"Sum of a+b+c is \"+sum);

     }

     void add(double a, double b)             {

        double sum = a + b;
        System.out.println(\"Sum of a+b is \"+sum);
     }

     void add(String s1, String s2)

     {
       String s = s1+s2;
       System.out.println(s);
     }
}

No comments: