Beginner 20 min read

Method Overloading

By the end of this lesson, you'll be able to:

  • Define method overloading
  • Write two overloaded versions of the same method name
  • Explain how Apex decides which overload to call

Prerequisites: "Return Values"

Same name, different parameters

public Decimal calculateArea(Decimal side) {
    return side * side; // square
}

public Decimal calculateArea(Decimal length, Decimal width) {
    return length * width; // rectangle
}

Both methods are named calculateArea, but one takes a single Decimal and the other takes two. Apex tells them apart by their parameter list — this is called overloading.

Apex picks the right one for you

Decimal squareArea = calculateArea(5);        // calls the one-parameter version → 25
Decimal rectArea = calculateArea(4, 6);       // calls the two-parameter version → 24

You don't have to name them calculateSquareArea and calculateRectangleArea — Apex matches each call to the overload whose parameter list fits, based purely on how many arguments (and of what type) you pass.

A real business example: Subscription Billing

public Decimal calculatePrice(Decimal monthlyRate) {
    return monthlyRate;
}

public Decimal calculatePrice(Decimal monthlyRate, Integer months) {
    return monthlyRate * months;
}

Decimal oneMonth = calculatePrice(299);        // 299
Decimal sixMonths = calculatePrice(299, 6);    // 1794

A billing system naturally has both a "price this month" and a "price for N months" calculation — overloading lets both live under one intuitive name instead of two awkwardly different ones.

What does NOT make a valid overload

Changing only the return type while keeping the same parameter list is not a valid overload — Apex (like most languages) can't tell two methods apart based on return type alone, since the call site doesn't always make the return type obvious.

Exercise

Write two overloaded versions of a method named formatName: one that takes just a String fullName and returns it as-is, and one that takes a String firstName and a String lastName and returns them combined with a space.

Show hint

The two versions differ by parameter count.

APEX

Method Overloading Quiz

1. What makes two methods valid overloads of each other?

Log in to submit the quiz and save your score.

My Notes

Log in to keep private notes on this lesson.

Questions about this lesson

No questions yet — be the first to ask.

Log in to ask a question about this lesson.

Summary

Overloading lets several methods share the same name as long as their parameter lists differ — Apex picks the right one automatically based on what you pass in.