What is Methods Overloading

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() {
    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:


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

Automatic type conversions apply to overloading

 
class OverloadDemo {
  void test() {
    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:


No parameters
a and b: 10 20
Inside test(double) a: 88.0
Inside test(double) a: 123.2
java2s.com  | Contact Us | Privacy Policy
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.