Commit 10b384a
committed
feat: Add MethodOverloading to demonstrate overloaded max methods
WHAT the code does:
Defines a MethodOverloading class with two static overloaded max methods:
- max(byte x, int y) compares a byte and an int, returning the larger value.
- max(float x, float y) compares two floats, returning the larger value.
main() demonstrates usage by calling:
- max(a, b) where a is byte and b is byte (promoted to int)
- max(10.9f, 5) where 5 is implicitly promoted to float.
WHY this matters:
Demonstrates method overloading in Java:
- Same method name but different parameter signatures.
- Compiler decides which method to call based on argument types and conversions.
Reinforces type promotion rules (byte to int, int to float).
Highlights how Java resolves overloaded methods at compile time.
HOW it works:
In main():
- Two byte variables a = 10, b = 5 are passed to max(byte, int).
b is promoted to int, method returns 10.
- For max(10.9f, 5), the int literal 5 is promoted to float.
max(float, float) executes and returns 10.9.
Outputs show the correct maximum values based on type and overload resolution.
Tips and gotchas:
Overloading is resolved at compile time, not runtime; this is not polymorphism.
Implicit type promotion can cause unexpected method resolution if multiple overloads exist.
Be cautious with mixed primitive and wrapper arguments, as autoboxing can create ambiguity.
For generality, prefer Math.max() overloads in production, but this example is educational.
Use-cases:
Educational demonstration of method overloading and type promotion.
Useful in API design where methods handle different input types but provide unified functionality.
Foundation for understanding overload resolution rules and type casting in Java.
Short key: class-methodoverloading max-overloads type-promotion.
Signed-off-by: https://github.com/Someshdiwan <[email protected]>1 parent e5bde3e commit 10b384a
1 file changed
+7
-13
lines changed| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
1 | | - | |
2 | | - | |
3 | | - | |
4 | | - | |
5 | | - | |
| 1 | + | |
| 2 | + | |
| 3 | + | |
| 4 | + | |
6 | 5 | | |
7 | | - | |
8 | | - | |
9 | | - | |
| 6 | + | |
10 | 7 | | |
11 | 8 | | |
12 | 9 | | |
13 | 10 | | |
14 | 11 | | |
15 | | - | |
16 | | - | |
| 12 | + | |
17 | 13 | | |
18 | 14 | | |
19 | 15 | | |
20 | | - | |
21 | | - | |
22 | 16 | | |
23 | | - | |
| 17 | + | |
0 commit comments