Method Overloading Basics
Part of the Object Oriented Programming section of Coddy's Java journey — lesson 28 of 87.
Polymorphism means "many forms." In Java, it allows objects to behave differently based on context. One form of polymorphism is method overloading, also called compile-time polymorphism because Java determines which method to call during compilation.
Method overloading lets you define multiple methods with the same name but different parameters. The compiler distinguishes between them based on the number, type, or order of parameters:
public class Calculator {
public int add(int a, int b) {
return a + b;
}
public int add(int a, int b, int c) {
return a + b + c;
}
public double add(double a, double b) {
return a + b;
}
}When you call add(5, 3), Java uses the first method. Calling add(5, 3, 2) triggers the second, and add(5.0, 3.0) invokes the third. The compiler picks the right version based on the arguments you provide.
Note that changing only the return type is not valid overloading. The parameter list must differ:
// NOT valid overloading - won't compile
public int getValue() { return 1; }
public double getValue() { return 1.0; } // Error!You've actually seen overloading before with constructor overloading. Method overloading follows the same rules and provides flexibility by letting one method name handle different input scenarios.
Challenge
EasyLet's build a message formatter that demonstrates method overloading by providing multiple ways to format messages. You'll create a utility class with several overloaded format methods that handle different input scenarios.
You'll organize your code across two files:
MessageFormatter.java: Create a class that provides flexible message formatting through overloaded methods. Your formatter should have:- A method
format(String message)that returns the message wrapped in brackets:[message] - A method
format(String message, int repeatCount)that returns the message repeated the specified number of times, separated by spaces - A method
format(String message, String prefix)that returns the message with the prefix attached:prefix: message - A method
format(String message, String prefix, String suffix)that returns:prefix: message (suffix)
- A method
Main.java: Demonstrate all four overloaded methods working together. You'll receive four inputs: a message (String), a repeat count (int), a prefix (String), and a suffix (String). Create a MessageFormatter and call each version of theformatmethod, printing each result on its own line:- First, format with just the message
- Second, format with the message and repeat count
- Third, format with the message and prefix
- Fourth, format with the message, prefix, and suffix
You will receive four inputs: the message text, how many times to repeat it, a prefix string, and a suffix string.
For example, if the message is "Hello", repeat count is 3, prefix is "INFO", and suffix is "done", your output should show four different formatted versions of the same message, each using a different overloaded method!
Cheat sheet
Method overloading allows you to define multiple methods with the same name but different parameters. This is also called compile-time polymorphism because Java determines which method to call during compilation.
The compiler distinguishes overloaded methods based on the number, type, or order of parameters:
public class Calculator {
public int add(int a, int b) {
return a + b;
}
public int add(int a, int b, int c) {
return a + b + c;
}
public double add(double a, double b) {
return a + b;
}
}When calling add(5, 3), Java uses the first method. Calling add(5, 3, 2) triggers the second, and add(5.0, 3.0) invokes the third.
Important: Changing only the return type is not valid overloading. The parameter list must differ:
// NOT valid overloading
public int getValue() { return 1; }
public double getValue() { return 1.0; } // Error!Try it yourself
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// Read inputs
String message = scanner.nextLine();
int repeatCount = Integer.parseInt(scanner.nextLine());
String prefix = scanner.nextLine();
String suffix = scanner.nextLine();
// TODO: Create a MessageFormatter object
// TODO: Call format with just the message and print the result
// TODO: Call format with message and repeatCount and print the result
// TODO: Call format with message and prefix and print the result
// TODO: Call format with message, prefix, and suffix and print the result
}
}
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Object Oriented Programming
1Fundamentals of OOP
External FilesIntroduction to OOPClasses vs ObjectsThe this KeywordMethodsFields (Attributes)Constructor MethodConstructor OverloadingRecap - Simple Calculator4Inheritance
Basic Inheritance (extends)The super KeywordMethod Overriding (@Override)Constructor ChainingThe Object ClassSingle & Multilevel InheritWhy No Multi Class InheritRecap - Employee Hierarchy7Special Methods & Object Class
toString() Methodequals() and hashCode()clone() MethodcompareTo() and ComparableComparator InterfaceRecap - Custom Sorting2Access Modifiers & Encapsulate
Access Levels OverviewGetter and Setter MethodsInformation HidingThe final KeywordRecap - Bank Account Manager5Polymorphism
Method Overloading BasicsMethod Overriding (Run-Time)Upcasting and DowncastingThe instanceof OperatorAbstract Classes and MethodsRecap - Shape Calculator8Advanced OOP Concepts
Composition vs InheritanceAggregation vs CompositionInner Nested & Anonymous ClassEnums and Enum MethodsRecords (Java 16+)Sealed Classes (Java 17+)3Class Props & Static Member
Instance vs Static VariablesStatic MethodsStatic BlocksConstants (static final)Recap - Counter & Utility6Interfaces & Abstract Classes
Introduction to InterfacesImplementing InterfacesMulti Interface ImplemenDefault & Static in InterfaceAbstract Classes vs InterfacesFunctional InterfacesRecap - Payment System