3) Java Methods Lesson

What is Method Overloading in Java?

4 min to complete · By Ryan Desmond

Overloading is one of the ways Java implements polymorphism. Both methods and constructors can be overloaded by having two or more versions with slightly different definitions.

How to Overload a Method in Java

To overload a method, two or more methods with the same exact name must be created. However, the methods must differ in at least one of the following ways:

  • the type of parameter
  • the number of parameters

Different Return Type 

It is important to remember that different return types are not sufficient information for Java to implement overloading.

Java Method Overloading Example

Method overloading allows for the dynamic use of a method. A good example of method overloading is a method that performs addition. If you were to create a method that adds one or more numbers together, you would want a user to be able to use that method with two int, three int, two double, and the options go on.

Take a look at how you can create a few methods that satisfy the addition of numbers. This is a single method addition() being overloaded three times.

class Main {
  public static void main(String[] args){
    // notice how you're calling addition() 
    // three different ways below
    int a = addition(2, 2);
    int b = addition(2, 2, 2);
    int c = addition(1.1, 2.2, 3.3);

    System.out.println(a);
    System.out.println(b);
    System.out.println(c);
  }

  // method one - takes in two ints and 
  // returns the sum as an int
  static int addition(int a, int b){
    return a + b;
  }

  // method two - takes in three ints and returns 
  // the sum as an int
  static int addition(int a, int b, int c){
    return a + b + c;
  }

  // method three - takes in three doubles and 
  // returns the sum as an int
  static int addition(double a, double b, double c){
    return ((int)(a + b + c));
  } 
}

The method addition() can be invoked by being passed two int arguments, three int arguments, or three double arguments. The JVM will decide which method to execute based on the number of arguments being passed to an overloaded method.

Common Method Overloading Example in Java

You have been using method overloading since your first program. When you want to print something, you use the System.out.println(), and you're able to pass the method to any number of arguments of all kinds. This is because this method has been overloaded many times to offer any combination of arguments.

Summary: What is Method Overloading in Java

  • Overloading happens when two or more methods have the same name but different properties
  • An overloaded method must have either a different number of parameters or accept different parameter types
  • System.out.println() is a commonly used example of method overloading