Method Overloading in Java | Java for Beginner | Java Language | Same Name Different Arguments.

Method Overloading

In Java it is possible to define two or more methods within the same class that share the same name, as long as their parameter declarations are different.

When this is the case, the methods are said to be overloaded, and the process is referred to as method overloading. Method overloading is one of the ways that Java supports polymorphism.

When an overloaded method is invoked, Java uses the type and/or number of arguments as its guide to determine which version of the overloaded method to actually call.

Here is a simple example that illustrates method overloading:


class OverloadDemo
{
   void test()
   {
      System.out.println("No parameters");
   }
   // Overload test for one integer parameter.
   void test(int a)
   {
      System.out.println("a: " + a);
   }
   // Overload test for two integer parameters.
   void test(int a, int b)
   {
      System.out.println("a and b: " + a + " " + b);
   }
   // overload test for a double parameter
   double test(double a)
   {
      System.out.println("double a: " + a);
      return a*a;
   }
}

class Overload
{
   public static void main(String args[])
   {
      OverloadDemo ob = new OverloadDemo();
      double result;
      // call all versions of test()
      ob.test();
      ob.test(10);
      ob.test(10, 20);
      result = ob.test(123.25);
      System.out.println("Result of ob.test(123.25): " + result);
   }
}



Output:

No parameters
a: 10
a and b: 10 20
double a: 123.25
Result of ob.test(123.25): 15190.5625


Method overloading supports polymorphism because it is one way that Java implements the “one interface, multiple methods” paradigm.

When you overload a method, each version of that method can perform any activity you desire. There is no rule stating that overloaded methods must relate to one another.

Post a Comment

1 Comments