Methods Overloading

In this chapter you will learn:

  1. How to overload methods with different parameters
  2. How does automatic type conversions apply to overloading

Overload methods

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.

The following example illustrates method overloading:

class OverloadDemo {
  void test() {//from  java 2 s . 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:

Automatic type conversions apply to overloading

The following code demonstrates method overloading and data type promotion.

class OverloadDemo {
  void test() {/* j ava 2s  .  c  o 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. What is the syntax to declare main() method
  2. How to pass command line arguments to main method