Skip to content

Commit f79f358

Browse files
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

File tree

1 file changed

+7
-4
lines changed

1 file changed

+7
-4
lines changed

Section10Methods/Methods 2.O/src/Overloading.java

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,18 @@
11
public class Overloading {
22
public static void main(String[] args) {
3-
// fun(67);
4-
// fun("Kunal Kushwaha");
5-
int ans = sum(3, 4, 78);
6-
System.out.println(ans);
3+
fun(7);
4+
fun("Somesh Diwan");
5+
6+
int ans = sum(3, 4, 78);
7+
System.out.println(ans);
78
}
89

10+
//First method called.
911
static int sum(int a, int b) {
1012
return a + b;
1113
}
1214

15+
//Second method called.
1316
static int sum(int a, int b, int c) {
1417
return a + b + c;
1518
}

0 commit comments

Comments
 (0)