Java Method Overload

In this chapter you will learn:

  1. What is method overloading
  2. Note for Java Method Overload
  3. Example - How to overload methods with different parameters
  4. Example - How does automatic type conversions apply to overloading

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 .  ja v a 2s.  c om*/
    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() {//ww  w .  j ava 2s  .co m
    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:

Next chapter...

What you will learn in the next chapter:

  1. How to overload a constructor
  2. Example - Java Constructors Overload
  3. How to invoke overloaded constructors through this()