Java Method Overload

Description

Java allows 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.

Note

Overloaded methods have the same name but different parameters. Overloaded methods must differ in the type and/or number of their parameters. Overloaded methods may have different return types. return type alone is insufficient to distinguish two methods.

Example

The following example illustrates method overloading:

 
class OverloadDemo {
  void test() {//from   ww w .  j a v  a2s .com
    System.out.println("No parameters");
  }
  void test(int a) {
    System.out.println("a: " + a);
  }
  void test(int a, int b) {
    System.out.println("a and b: " + a + " " + b);
  }
  double test(double a) {
    System.out.println("double a: " + a);
    return a * a;
  }
}
public class Main {
  public static void main(String args[]) {
    OverloadDemo ob = new OverloadDemo();
    ob.test();
    ob.test(10);
    ob.test(10, 20);
    double result = ob.test(123.25);
    System.out.println("Result of ob.test(123.25): " + result);

  }
}

This program generates the following output:

Example 2

The following code demonstrates method overloading and data type promotion.

 
class OverloadDemo {
  void test() {/* w  w  w .j ava 2  s  .  c  om*/
    System.out.println("No parameters");
  }
  void test(int a, int b) {
    System.out.println("a and b: " + a + " " + b);
  }
  void test(double a) {
    System.out.println("Inside test(double) a: " + a);
  }
}

public class Main {
  public static void main(String args[]) {
    OverloadDemo ob = new OverloadDemo();
    int i = 88;
    ob.test();
    ob.test(10, 20);

    ob.test(i); // this will invoke test(double)
    ob.test(123.2); // this will invoke test(double)
  }
}

This program generates the following output:





















Home »
  Java Tutorial »
    Java Language »




Java Data Type, Operator
Java Statement
Java Class
Java Array
Java Exception Handling
Java Annotations
Java Generics
Java Data Structures