BIT401 ยท 0 ยท 5 marks
What is method overloading? Explain with example.
What is method overloading? Explain with example. [5]
Advanced Java ProgrammingChapter 1: Object-Oriented Programming FundamentalsMethod overloading and overriding
Quick answer
Method overloading is a feature of Object-Oriented Programming that allows a class to have multiple methods with the same name but different parameters. It is a way to implement compile-time (static) polymorphism.
Method Overloading
Definition
The methods must differ in:
- Number of parameters, OR
- Type of parameters, OR
- Order of parameters
Rules for Method Overloading
- Methods must have the same name
- Methods must have different parameter lists
- Return type alone is NOT sufficient for overloading
- Access modifiers can be different
Example
class Calculator {
// Method 1: Add two integers
public int add(int a, int b) {
return a + b;
}
// Method 2: Add three integers (different number of parameters)
public int add(int a, int b, int c) {
return a + b + c;
}
// Method 3: Add two doubles (different type of parameters)
public double add(double a, double b) {
return a + b;
}
// Method 4: Add int and double (different order/type)
public double add(int a, double b) {
return a + b;
}
}
// Usage
public class Main {
public static void main(String[] args) {
Calculator calc = new Calculator();
System.out.println(calc.add(5, 10)); // Calls Method 1: 15
System.out.println(calc.add(5, 10, 15)); // Calls Method 2: 30
System.out.println(calc.add(5.5, 10.5)); // Calls Method 3: 16.0
System.out.println(calc.add(5, 10.5)); // Calls Method 4: 15.5
}
}
Advantages
- Improves code readability and usability
- Makes the API intuitive (same operation, same method name)
- Reduces confusion with multiple method names for similar operations
Short on time? The 1, 5 and 10 mark versions of this answer, flashcards and practice sets come with a program pass.