Java Method Overloading

Introduction

Java can define two or more methods within the same class that have the same name.

Their parameter declarations are must be different.

The overloaded methods must differ in the type and/or number of their parameters.

This is called the he methods overloading.

When an overloaded method is called, Java uses the type and/or number of arguments to choose which overloaded method to call.

The return type alone is insufficient to distinguish two method.

// Demonstrate method overloading.
public class Main{
  void test() {//from ww w  . j  a va  2  s.  com
    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;
  }
  public static void main(String args[]) {
    Main ob = new Main();
    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);
  }
}



PreviousNext

Related