0/30 Days Completed 0 Learning Days
Day 24 of 30 · Week 4 — OOPs Through Java
Method overloading: deeper practice
1 Learn
Overloaded methods must differ in their parameter list: number, types or order of parameters.
Changing only the return type is NOT enough — Java would not know which one to call.
Overloading is common: System.out.println itself is overloaded for int, double, String and more.
2 See the Code
Java
public class Printer {
static void show(int x) { System.out.println("int: " + x); }
static void show(double x) { System.out.println("double: " + x); }
static void show(String s) { System.out.println("text: " + s); }
static void show(String s, int times) {
for (int i = 0; i < times; i++) System.out.println(s);
}
public static void main(String[] args) {
show(5);
show(2.5);
show("hi");
show("ok", 2);
}
}- Java picks the version whose parameters match the arguments.
- show("ok", 2) matches the two-parameter version.
Output
int: 5 double: 2.5 text: hi ok ok
3 Practice
- Write overloaded max(int, int), max(int, int, int) and max(double, double).
Try it in your own Java setup or write it in the Practice Notebook.
4 Quick Check
1. Which pair is a valid overload?
2. Overloading is decided at...
Step 5
Answer and check the Quick Check above to unlock this.