Java Method Overloading

Java Method Overloading

  • Method overloading is the ability to define multiple methods with the same name in a class.
  • Compiler selects the proper method from those who are overloaded during compilation.
  • Compiler picks the correct method based on the number and type of all the parameters passed to the method.
  • Differentiation only in return type between methods does not provide overloaded methods.
    Method Overloading example:
    public class MethodOverloading {
    // 1. printlist for integers (overloaded method)
      public void printList(Integer[] list) {
        for (Object o : list) {
          System.out.println(o);
        }
      }
    // 2. printlist for strings (overloaded method)
      public void printList(String[] list) {
        for (String o : list) {
          System.out.println(o);
        }
      }
    
      public static void main(String args[]) {
        String[] priceCat = {"Low", "Middle", "High"};
        // this will use the 2. printlist method
        new MethodOverloading().printList(priceCat);
        Integer[] prices = {56, 66, 78};
         // this will use the 1. printlist method
        new MethodOverloading().printList(prices);
      }
    }
    The result of this is:
    Low
    Middle
    High
    56
    66
    78
    You can download this example here (needed tools can be found in the right menu on this page).
© 2010 by Finnesand Data. All rights reserved.
This site aims to provide FREE programming training and technics.
Finnesand Data as site owner gives no warranty for the correctness in the pages or source codes.
The risk of using this web-site pages or any program codes from this website is entirely at the individual user.