Showing posts with label function overloading. Show all posts
Showing posts with label function overloading. Show all posts

Sunday, 1 November 2015

Java Method Overloading

Method Overloading in Java

In java method overloading means we are using overloading methods.That means if a class have multiple methods by same name but different parameters, it is known as Method Overloading.

If we need to perform one operation and as explained above the method name increases the readability of the program.

Method overloading is a type of polymorphism, called static polymorphism.

Different ways to overload the method
There are two ways to overload the method in java
  1. By changing number of arguments
  2. By changing the data type

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

class MethodOverloading
{
    public void display(int a)
    {
         System.out.println(a);
    }
    public void display(int a, char ch)  
    {
         System.out.println(ch+ " "+a);
    }
}
class Sample
{
   public static void main(String args[])
   {
       MethodOverloading abc= new MethodOverloading();
       abc.display(5);
       abc.display(5,'A');
   }
}
Output:
5
A 5

2)Example of Method Overloading by changing data type of argument

class MethodOverloading {     void sum(int a,int b){System.out.println(a+b);}     void sum(double a,double b){System.out.println(a+b);}        public static void main(String args[]){     MethodOverloading abc=new MethodOverloading ();     abc.sum(5.5,5.5);     abc.sum(10,10);        }   }  
Output:
11.0
20