Modal Box

Overloading in java

Function or constructor may be overloaded in java.
 ⇒ Function Or Method overloading means when a class has more than one function with the same name but different signature.
 ⇒ Function must have the different number of arguments or different order of arguments.

Overloading may be defined as following:

class OverloadingDemo
{
   void display()
    {
       System.out.println("This is default function");
    }
   void display(String msg)
     {
        System.out.println(msg);
     }
}

class TestMain
{
  public static void main(String args[])
   {
     OverloadingDemo obj= new OverloadingDemo();
     obj.display(); //function without parameter is called as we don't pass any string here.
     obj.display("Sharp Tutorial"); // function with String argument is being called.
   }
}

Overloading Need can be understood better with the following example of area calculation.

class Area
{
  int a1(int l,int b) //function for rectangle area calculation.
   {
      return (l*b);
   }
  int a2(int l) //function for square area calculation
   {
      return (l*b);
   }
}

In the above example, user needs to remember either a1 or a2 method is called.
If the user passes different parameters to different function, then it will throw error.
But if we give same name to function then based on the arguments, the function will be called automatically.

class Area
{
   int areaCal(int l,int b) //function for rectangle area calculation.
    {
      return (l*b);
    }
   int areaCal(int l) //function for square area calculation with same name.
    {
      return (l*l);
    }
}

class testMain { public static void main(String args []) { Area a1= new Area(); int k; k=a1.areaCal(10,20); // no need to remember which function to call k=a1.areaCal(15); System.out.println("Area is"+k); } }

Video/ C Introduction

Watch video in full size
Wordpress Social Share Plugin powered by Ultimatelysocial