Overloading Methods

Methods

Overloading Methods

🙋 Need help? Ask an expert now!

In Java, the concept of "overloading" is when two or more methods of a class have the same name but different "parameter lists". In this special case, when a method is called, the program calls the correct method by checking the parameters. To understand this concept further, let's think back to when we were working with the Math class. When we used the method Math.abs(), we experienced the concept of overloading as the method had four different choices for the parameter; the data types int, double, float, and long. Let's dive into how we can overload a method.

OverloadingMethodsExample.java
package exlcode;

public class OverloadingMethodsExample {

  public static float exampleVariableOne = 3.14f;
  public static double exampleVariableTwo = Math.PI;

  public static void main(String[] args) {
    print(exampleVariableOne);
    print(exampleVariableTwo);
  }

  // two identical methods with different parameters
  // takes in float value as a parameter
  public static void print(float parameterOne) {
    System.out.println("float: " + parameterOne);
  }
  // takes in a double value as a parameter
  public static void print(double parameterOne) {
    System.out.println("double: " + parameterOne);
  }
}

The method named print() is overloaded when we create two methods with the same name containing different parameters. One takes in double values while the other takes float values. The only difference between the methods has to be the parameters in order for it to be considered "overloading". One rule to keep in mind when working with overloaded methods is that return types for the methods cannot be the only thing that separates one method from the other. For example, creating two methods with the headers public int methodA() and public double methodA() will result in an error.

Edit Me on GitHub!

Application Question

Consider the following code segment:

public class ExampleClass{
  public void calculateNum(int paramOne){
    /* implementations not shown */
  }
  public void calculateNum(int paramOne, int paramTwo){
    /* implementations not shown */
  }
  public void calculateNum(int paramOne, String paramTwo){
    /* implementations not shown */
  }
}

Which of the following methods can be added to ExampleClass without causing a compile-time error?

I.

public void calculateNum(int paramThree){
  /* implementation not shown */
}

II.

public void calculateNum(String paramOne, int paramTwo){
  /* implementation not shown */
}

III.

public void calculateNum(int paramOne, int paramTwo, String paramThree){
  /* implementation not shown */
}