Method overloading: declaring methods with the same name

Learn what it is and how to do Method overloading in Java
In our article about parameters and arguments in Java, we show an example of a method that takes a number and returns the square of that number.

But this method has a limitation: it only received integers.
And if you want to create methods with float? double?

Make an overload.



Methods overloading: How to create multiple methods with the same name


The term comes from the fact overload declare multiple methods with the same name, we are loading the app with the 'same' method.
The only difference between these methods are its parameters and/or return type.

For example, we declare, in the same application, square two methods: one that receives and returns integers and another that receives and returns double type.

public static int square(int num){
int sqr;
sqr = num * num;
return sqr;
}



public static double square(double num){
double sqr;
sqr = num * num;
return sqr;
}


When we declare these two methods, we are doing some method overloading in Java.
What happens, then, when we called the function, since there are two?

Although the names are the same, they act so different and occupy different spaces in memory because they are dealing with different types of variables.

When we invoke the method with an integer as an argument, Java is smart enough to properly invoke the method that was declared with integer as parameter.
If we invoke the method using a double as an argument, the method to be executed will be the one that was declared with the type double in its parameter.

See a Java code example:

public class Overloading {
    public static int square(int num){
        int sqr;
        sqr = num * num;
        return sqr;
    }


    public static double square(double num){
        double sqr;
        sqr = num * num;
        return sqr;
 }
    
    public static void main(String[] args){
        System.out.println("2 squared: " + square(2));
        System.out.println("PI squared: " + square( Math.PI ));
    }

}

No comments: