Skip to content

Commit b48f970

Browse files
committed
feat: Add AddOverloadDemo class demonstrating method overloading
WHAT the code does: - Defines `AddOverloadDemo` with three overloaded `add()` methods: 1. **No parameters** → adds hardcoded numbers (10 + 20) and prints result. 2. **Two parameters** → returns sum of two integers. 3. **Three parameters** → calculates sum of three integers and prints result. - `main()` demonstrates calling all three variations. WHY this matters: - Showcases **method overloading** in Java — same method name, different parameter lists. - Demonstrates flexibility in designing APIs with multiple usage options. - Highlights both returning values and printing results. HOW it works: 1. `obj.add()` → calls no-arg method → prints `"Sum (no parameters): 30"`. 2. `obj.add(15, 25)` → calls two-arg method → returns 40 → printed in main. 3. `obj.add(5, 10, 20)` → calls three-arg method → prints `"Sum (three parameters): 35"`. Tips & gotchas: - Overloading is determined at **compile time** (static polymorphism). - Cannot overload methods by return type alone — parameter list must differ. - Ensure method signatures are distinct enough to avoid ambiguity. - Consistency matters: mixing printing vs returning can confuse API users. Use-cases: - Educational example for **compile-time polymorphism**. - Practical for calculator-like utilities with multiple input forms. - Foundation for designing libraries where methods accept variable arguments. - Interview prep problem for method overloading. Short key: class-add overload demo-method-overloading. Signed-off-by: https://github.com/Someshdiwan <[email protected]>
1 parent 2128f89 commit b48f970

File tree

1 file changed

+3
-5
lines changed

1 file changed

+3
-5
lines changed

Section10Methods/PracticeProblems/src/AddOverloadDemo.java

Lines changed: 3 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,24 +1,22 @@
11
public class AddOverloadDemo {
2-
3-
// Method 1: No parameters, adds hardcoded numbers
2+
// Method 1: No parameters, adds hardcoded numbers.
43
void add() {
54
int a = 10, b = 20;
65
int sum = a + b;
76
System.out.println("Sum (no parameters): " + sum);
87
}
98

10-
// Method 2: Two parameters, returns the sum
9+
// Method 2: Two parameters, returns the sum.
1110
int add(int x, int y) {
1211
return x + y;
1312
}
1413

15-
// Method 3: Three parameters, prints the sum
14+
// Method 3: Three parameters, prints the sum.
1615
void add(int x, int y, int z) {
1716
int sum = x + y + z;
1817
System.out.println("Sum (three parameters): " + sum);
1918
}
2019

21-
// Main method to call all add methods
2220
public static void main(String[] args) {
2321
AddOverloadDemo obj = new AddOverloadDemo();
2422

0 commit comments

Comments
 (0)