Commit f79f358
committed
feat: Demonstrate method overloading with sum() and fun() methods
WHAT the code does:
- Defines a class `Overloading` to showcase Java method overloading.
- `sum(int, int)` → adds two integers.
- `sum(int, int, int)` → adds three integers.
- `fun(int)` → prints a message and integer value.
- `fun(String)` → prints a message and string value.
- `main()` calls both `fun()` versions and the overloaded `sum()`.
WHY this matters:
- Demonstrates **compile-time polymorphism** (method overloading) in Java.
- Shows how the compiler selects the correct method based on argument type and count.
- Useful for creating cleaner APIs with multiple input variations.
HOW it works:
1. `fun(7)` → calls `fun(int)` → prints "first one" and `7`.
2. `fun("Somesh Diwan")` → calls `fun(String)` → prints "Second one" and name.
3. `sum(3, 4, 78)` → calls `sum(int, int, int)` → returns `85`, printed to console.
Tips & gotchas:
- Overloading depends on **method signature** (name + parameter list).
- Return type alone cannot differentiate overloaded methods.
- Ambiguity can occur if compiler cannot resolve best match (e.g., `fun(null)` matches both `fun(String)` and `fun(Object)` if defined).
- For readability, ensure overloaded methods logically relate (like multiple `sum` variations).
Use-cases:
- Calculator utilities with variable argument counts.
- Logging methods accepting different data types.
- Educational examples to understand **polymorphism**.
- Cleaner APIs by avoiding multiple method names for similar tasks.
Short key: class-overloading-sum-fun-demo.
Signed-off-by: https://github.com/Someshdiwan <[email protected]>1 parent 355e991 commit f79f358
1 file changed
+7
-4
lines changed| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
1 | 1 | | |
2 | 2 | | |
3 | | - | |
4 | | - | |
5 | | - | |
6 | | - | |
| 3 | + | |
| 4 | + | |
| 5 | + | |
| 6 | + | |
| 7 | + | |
7 | 8 | | |
8 | 9 | | |
| 10 | + | |
9 | 11 | | |
10 | 12 | | |
11 | 13 | | |
12 | 14 | | |
| 15 | + | |
13 | 16 | | |
14 | 17 | | |
15 | 18 | | |
| |||
0 commit comments