DEV Community

Cover image for Function Overloading
Mohammad Tomaraei
Mohammad Tomaraei

Posted on

Function Overloading

I recently came across a key feature of object-oriented programming that has been implemented in some programming languages and is commonly known as function overloading or method overloading.

In a nutshell, it allows defining multiple functions or methods with the same name but different implementations.

It could come quite handy in situations where a method may take in different configurations of arguments and return a different type in each case.

What’s even more interesting about function overloading is that while it is considered illegal in many programming languages like Python and PHP, others like C++, C#, Java, Swift, and Kotlin have it built-in.

I found out about polymorphism and function overloading in a Java course through a multiple-choice question.

Here’s the example they used:

public class Zap {
    static boolean zap() { return true; }
    static int zap(boolean x) { return 0; }
    static double zap(int x) { return 0.5; }
    static String zap(double x) { return "Zap!"; }
    static boolean zap(String x) { return false; }
    public static void main(String[] args) {
        System.out.println(zap(zap(zap(zap(1)))));
    }
}
Enter fullscreen mode Exit fullscreen mode

What do you think is the output?

a. true
b. 0
c. 0.5
d. Zap!
e. false

With the help of a debugger we can trace our nested method calls:

debugger

Java determines which method definitions to use for each method call based on the type of the actual argument.

The inner-most zap takes in an integer, so Java will choose the third method definition. It returns type Double and therefore the next zap is going to use the fourth method definition, and so on.

This post was originally published on my blog where I write all about tech.

Oldest comments (0)