Java Method Overloading Example

In Java, if the class has two or more methods having the same name but different in parameters, this process is known as Method Overloading.

The compiler will resolve the call to a correct overloaded method depending on the actual number and/or types of the passed parameters. We can use Method overloading to achieve Java compile-time polymorphism.
The main advantage of method overloading increases the readability of the program.

Java Method Overloading Example

Here is a simple example that illustrates method overloading:
public class Foo {

    public void foozzy(String p, int q) {
        System.out.println("Called foozzy(" + p + ", " + q + ")");
    }

    // different number of arguments
    public void foozzy(String p, int q, int w) {
        System.out.println("Called foozzy(" + p + ", " + q + ", " + w + ")");
    }
    
    // different order of arguments
    public void foozzy(int q, String p) {
        System.out.println("Called foozzy(" + q + ", " + p + ")");
    }
    
    // different types of arguments
    public void foozzy(int p, int q) {
        System.out.println("Called foozzy(" + p + ", " + q + ")");
    }
    
    // not valid - different return type
    /* 
    public boolean foozzy(String p, int q) {
        System.out.println("Called foozzy(" + p + ", " + q + ")");
    }
    */
}
Let's test the above code contains overloaded methods with the main() method:
public class Main {

    public static void main(String[] args) {

        Foo foo = new Foo();
        
        foo.foozzy("text", 1);
        foo.foozzy(1, "text");
        foo.foozzy(-1, 1);
        foo.foozzy("text", -1, 1);
    }
}
Output:
Called foozzy(text, 1)
Called foozzy(1, text)
Called foozzy(-1, 1)
Called foozzy(text, -1, 1)
Read more about method overloading at Method Overloading in Java

Related Java OOPS Examples


Comments