Logo 
Search:

Java Articles

Submit Article
Home » Articles » Java » FundamentalRSS Feeds

Method Overloading

Posted By: Caleb Lopez     Category: Java     Views: 24360

This article explains about method overloading in java with different examples.

Method overloading means when two or more methods have the same name but a different signature. Signature of a method is nothing but a combination of its name ans the sequence of its parameter types. 

Advantages of method overloading

- It allows you to use the same name for a group of methods that basically have the same purpose.
- It provides an easy way to handle default parameter value. 

Assume that a method has one required parameter and two optional parameters. Three overloaded forms of this method can be defined. It can accept one, two or three parameters.

Best example of overloading method is println() method. This method have many overloaded forms where each of these accepts one argument of a different type. The type may be a boolean, char, int, long, flaot, double, String, char[] or Object.       

Syntax of Method Overloading

class clsName
{
      // variable declaration

     // constructor declaration

     // methods
    rtype1 mthName(cparam1)
    {
             // body of method
     }
 
     rtype2 mthName(cparm2)
     {
             // body of method
      }
}

Example of Method Overloading

Example 1 : Program that illustrates method overloading

class Sample
{
       int addition(int i, int j)
       {
               return i + j ;
        }
        
        String addition(String s1, String s2)
        {
                return s1 + s2;   
         }
        
        double addition(double d1, double d2)
        {
                return d1 + d2;   
         }
}

class AddOperation
{
      public static void main(String args[])
      {
              Sample sObj = new Sample();
   
              System.out.println(sObj.addition(1,2));
              System.out.println(sObj.addition("Hello ","World"));
              System.out.println(sObj.addition(1.5,2));
       }
}


Output

3
Hello World
3.5
  
Share: 


Didn't find what you were looking for? Find more on Method Overloading Or get search suggestion and latest updates.

Caleb Lopez
Caleb Lopez author of Method Overloading is from New York, United States.
 
View All Articles

 
Please enter your Comment

  • Comment should be atleast 30 Characters.
  • Please put code inside [Code] your code [/Code].

 
No Comment Found, Be the First to post comment!