← Java from Scratch
Lesson 25 of 88 · 10 XP
Method overloading
Theory and problem statement
Machine translation, not yet reviewed by a native speaker.
Several methods with the same name and different parameters — the compiler picks one by the arguments:
static int add(int a, int b) { return a + b; }
static double add(double a, double b) { return a + b; }
static int add(int a, int b, int c) { return a + b + c; }
add(1, 2); // int
add(1.5, 2); // double: the 2 gets widened
add(1, 2, 3);
You can't overload by the return type alone. System.out.println is an example: it has versions for int,
String, double, char, Object…
Task. Write three overloads of describe: int → int: <x>, double → double: <x> (2 decimal places),
String → String: <s> (<length>).
Sign up for free to solve this task right in your browser: code editor, running, test checks and hints.