Skip to content

Commit 10b384a

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

File tree

1 file changed

+7
-13
lines changed

1 file changed

+7
-13
lines changed
Lines changed: 7 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,23 +1,17 @@
1-
public class MethodOverloading
2-
{
3-
static int max(byte x, int y)
4-
{
5-
return x>y?x:y; //return if x is greater than y then return x otherwise return y.
1+
public class MethodOverloading {
2+
static int max(byte x, int y) {
3+
return x>y ? x:y;
4+
//return, if x is greater than y then, return x otherwise return y.
65
}
7-
8-
static float max(float x, float y)
9-
{
6+
static float max(float x, float y) {
107
if(x>y)
118
return x;
129
else
1310
return y;
1411
}
15-
public static void main(String[] args)
16-
{
12+
public static void main(String[] args) {
1713
byte a=10,b=5;
1814
System.out.println(max(a,b));
1915
System.out.println(max(10.9f,5));
20-
21-
2216
}
23-
}
17+
}

0 commit comments

Comments
 (0)