Java Method Overloading

In Java, several methods can be defined in a class with the same name but different parameters. That means, despite the same method name, the signature is different. The difference with these methods is therefore in the choice of the arguments. This procedure is called overloading a method.

Example

For example, we could imagine a method „sum“, which builds the sum of passed values and outputs it to the console. Two „sum“ methods could be defined, one taking two and the other three parameters to sum.

public class meineErstesProgramm {

    public static void main(String[] args) {

        // Call the method
        sum(2,3);
        sum(2,3,4);

    }

    // Summing two summands
    public static void sum(int x, int y) {
        System.out.println(x+y);
    }

    // Summing three summands
    public static void sum(int x, int y, int z) {
        System.out.println(x+y+z);
    }

}
5
9

Java decides which of the available methods is to be executed at runtime on the basis of the parameters passed (more precisely, on the basis of the data type and the number of parameters).

When to use method overloading

We will sometimes see the advantages of overloaded methods in algorithms. The user of an algorithm calls a method „x“, which in turn calls an auxiliary method „x“, but with supplemented parameters, and passes the result to the method „x“ called by the user. Overloading is also a common practice in inheritance chains to extend functions. We will discuss this in more detail in the advanced posts.

However, overloading a method must not be confused with overwriting a method! We will discuss this difference in more advanced articles.

Schreibe einen Kommentar