Skip to content

Overloading

  • Lesson
  • 2 min read
  • 5 of 7 in this chapter

What is overloading?

Sometimes, we want a method with the same name but different functionality based on how many variables are in the parameter.

We will be using overloading to create two methods named multiplyAll, which multiply the parameters and return that value.

First, we create our first method:

Java
public static int multiplyAll(int one, int two) {
return one * two;
}

Pretty easy. If you call it, you will get the product of one and two.

Now, let's create our overloaded method:

Java
public static int multiplyAll(int one, int two, int three) {
return one * two * three;
}

See how it has the same name, return type but different parameters. That's what defines this type of overloaded method.

Let's call them in the main method:

Java
System.out.println(multiplyAll(3,4));
System.out.println(multiplyAll(3,4,5));

Different Return Type

The main thing that allows for overloaded methods is the number and type of parameters. Due to this, we can change the return type freely:

Java
public static double multiplyAll(double value) {
return value * 2;
}

In that method, we feed in a double as parameter value, only to return twice of itself.

Java
System.out.println(multiplyAll(4.5));

All of these methods have the same name but vary in parameters. That's overloading!