Java Learner logo

Module 4: Methods and Code Reusability

Lesson focus

Method Overloading

Learn how to define multiple methods with the same name but different parameters, a feature known as overloading.

What is Method Overloading? Method overloading is a feature that allows a class to have more than one method with the same name, as long as their parameter lists are different.

Rules for Overloading: To overload a method, the method name must be the same, but the parameters must differ in at least one of these ways:

  • Number of parameters: add(int a, int b) vs. add(int a, int b, int c)
  • Data type of parameters: add(int a, int b) vs. add(double a, double b)
  • Order of parameters: process(int a, String b) vs. process(String b, int a)

Note: The return type of the method does not matter for overloading. You cannot have two methods with the same name and same parameters but different return types.

Why is it Useful? Overloading allows you to create methods that perform the same general task but operate on different types or numbers of inputs. This makes your code more intuitive and flexible. The System.out.println() method is a perfect example of an overloaded method; it can accept an int, String, double, etc.

Mini-Exercise: Create a class with an overloaded method named display. One version should accept a String and print it. The second version should accept an int and print it. The third version should accept a String and an int and print both.

public class Greeter {
    public void greet() {
        System.out.println("Hello!");
    }

    // Overloaded method with one parameter
    public void greet(String name) {
        System.out.println("Hello, " + name + "!");
    }

    // Overloaded method with two parameters
    public void greet(String name, int times) {
        for (int i = 0; i < times; i++) {
            System.out.println("Hello, " + name + "!");
        }
    }
}

Lesson quiz

Which of the following is a valid way to overload a method `void myMethod(int x)`?

Next lesson →