Monday, March 23, 2015

Method overloading

Method Overloading is a feature that allows a class to have two or more methods having same name,for which their argument lists are different. i.e. it could be differ in
1. Number of parameters.
2. Data type of parameters.
3. Sequence of Data type of parameters.
Method overloading is also known as Static Polymorphism.
Points to Note:
1. Static Polymorphism is also known as compile time binding or early binding.
2. Static binding happens at compile time. Method overloading is an example of static binding where binding of method call to its definition happens at Compile time.
EXAMPLES

Example 1: Overloading – Different Number of parameters in argument list

When methods name are same but number of arguments are different.
class first
{
    public void disp(char c)
    {
         System.out.println(c);
    }
    public void disp(char c, int num)  
    {
         System.out.println(c + "="+num);
    }
}
class Second
{
   public static void main(String args[])
   {
       first obj = new First();
       obj.disp('a');
       obj.disp('a',10);
   }
}
Output:
a
a=10
In the above example – method disp() has been overloaded based on the number of arguments – We have two definition of method disp(), one with one argument and another with two arguments.

Example 2: Overloading – Difference in data type of arguments

In this example, method disp() is overloaded based on the data type of arguments – Like example 1 here also, we have two definition of method disp(), one with char argument and another with int argument.
class first
{
    public void disp(char c)
    {
        System.out.println(c);
    }
    public void disp(int c)
    {
       System.out.println(c );
    }
}

class second
{
    public static void main(String args[])
    {
        first obj = new First();
        obj.disp('a');
        obj.disp(5);
    }
}
Output:
a
5

Example3: Overloading – Sequence of data type of arguments

Here method disp() is overloaded based on sequence of data type of arguments – Both the methods have different sequence of data type in argument list. First method is having argument list as (char, int) and second is having (int, char). Since the sequence is different, the method can be overloaded without any issues.
class first
{
   public void disp(char c, int num)
   {
       System.out.println("I’m the first definition of method disp");
   }
   public void disp(int num, char c)
   {
       System.out.println("I’m the second definition of method disp" );
   }
}
class second
{
   public static void main(String args[])
   {
       first obj = new First();
       obj.disp('x', 51 );
       obj.disp(52, 'y');
   }
}
Output:
Im the first definition of method disp
Im the second definition of method disp

No comments:

Post a Comment