0% found this document useful (0 votes)
5 views2 pages

Java Method Overloading Explained

Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views2 pages

Java Method Overloading Explained

Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Method Overloading in Java

Introduction
Method Overloading occurs when two or more methods in a class have the same name but
different parameters (different type/number/order). It is an example of Compile-time Polymorphism.

Why Method Overloading?


- Increases readability
- Reduces code duplication
- Provides flexibility in method calls
Example: print(int x), print(double y), print(String s)

Rules of Method Overloading


- Same method name, but different parameters:
• Number of parameters
• Type of parameters
• Order of parameters
- Return type alone cannot differentiate overloaded methods

Example Code
class MathOperation {
int add(int a, int b) { return a + b; }
double add(double a, double b) { return a + b; }
int add(int a, int b, int c) { return a + b + c; }
}

Example Output
MathOperation m = new MathOperation();
[Link]([Link](5, 10)); // 15
[Link]([Link](5.5, 6.5)); // 12.0
[Link]([Link](1, 2, 3)); // 6

Advantages
- Code reusability
- Improves program readability
- Flexibility for different argument types
- Easy to maintain

Overloading vs Overriding
Real-life Examples
- [Link]() → overloaded for int, double, String, etc.
- [Link]() → overloaded for int[], double[], char[]

Conclusion
Method overloading is Compile-time polymorphism. It helps in code reusability, readability, and
flexibility. Widely used in Java libraries like println() and sort().

Feature Overloading (Compile-time) Overriding (Runtime)


Method name Same Same
Parameters Must be different Must be same
Return type Can be same/different Must be same/covariant
Polymorphism type Compile-time Runtime

You might also like