Skip to content

Commit c4c50b5

Browse files
committed
feat: Add MethodOverloading class with add() for int and double
WHAT the code does: - Defines a `MethodOverloading` class demonstrating method overloading. - Provides two `add()` methods: - `add(int a, int b)` → adds integers and prints result. - `add(double a, double b)` → adds doubles and prints result. - `main()` creates an object and calls both versions: - `obj.add(5, 7)` → calls integer version → prints `12`. - `obj.add(5.5, 7.5)` → calls double version → prints `13.0`. WHY this matters: - Demonstrates **compile-time polymorphism** in Java. - Shows how Java selects the correct method based on parameter types. - Highlights flexibility of using the same method name for related operations. HOW it works: 1. Compiler checks argument types during method call. 2. Resolves to correct method: - `(int, int)` → integer version. - `(double, double)` → double version. 3. Executes and prints result accordingly. Tips & gotchas: - Overloading requires different **parameter lists** (number or type). → Return type alone cannot differentiate methods. - Automatic type promotion (e.g., `obj.add(5, 7.5)`) will call the double version. - For mixed parameter types, be explicit to avoid ambiguity. Use-cases: - Calculator programs handling multiple numeric types. - Cleaner APIs by grouping logically similar operations. - Educational example for understanding **method overloading rules**. - Interview prep topic for compile-time polymorphism. Short key: class-methodover loading-int-double. Signed-off-by: https://github.com/Someshdiwan <[email protected]>
1 parent be360f0 commit c4c50b5

File tree

1 file changed

+4
-10
lines changed

1 file changed

+4
-10
lines changed

Section10Methods/PracticeProblems/src/MethodOverloading.java

Lines changed: 4 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,19 +1,13 @@
1-
//Addition of two numbers
2-
3-
public class MethodOverloading
4-
{
5-
void add(int a, int b)
6-
{
1+
public class MethodOverloading {
2+
void add(int a, int b) {
73
int result = a + b;
84
System.out.println(result);
95
}
10-
void add(double a, double b)
11-
{
6+
void add(double a, double b) {
127
double result = a + b;
138
System.out.println(result);
149
}
15-
public static void main(String[] args)
16-
{
10+
public static void main(String[] args) {
1711
MethodOverloading obj = new MethodOverloading();
1812
obj.add(5, 7); // Calls the method with int parameters
1913
obj.add(5.5, 7.5); // Calls the method with double parameters

0 commit comments

Comments
 (0)