Method Overloading - Notes by Shariq SP
Understanding Method Overloading in Java
Method overloading is a feature in Java that allows a class to have multiple methods with the same name but different parameter lists. These methods can perform similar tasks but accept different types or numbers of arguments.
Example 1: Method Overloading
In this example, we have a class Calculator
with multiple add
methods:
public class Calculator {
// Method to add two integers
public int add(int num1, int num2) {
return num1 + num2;
}
// Method to add three integers
public int add(int num1, int num2, int num3) {
return num1 + num2 + num3;
}
// Method to add two doubles
public double add(double num1, double num2) {
return num1 + num2;
}
}
Example 2: Method Overloading
In this example, we have a class Printer
with multiple print
methods:
public class Printer {
// Method to print an integer
public void print(int num) {
System.out.println("Printing integer: " + num);
}
// Method to print a double
public void print(double num) {
System.out.println("Printing double: " + num);
}
// Method to print a string
public void print(String text) {
System.out.println("Printing string: " + text);
}
}
Interview Questions on Method Overloading
- What is method overloading?
- Why is method overloading useful?
- Can method overloading change the return type of a method?
- What is the difference between method overloading and method overriding?
- How does Java determine which overloaded method to invoke?
Multiple Choice Questions (MCQs) - Method Overloading
- Which of the following statements about method overloading is true?
- Method overloading allows methods to have the same name and return type.
- Method overloading allows methods to have the same name but different return types.
- Method overloading allows methods to have different names but the same parameter types.
- Method overloading allows methods to have different names and different parameter types.
- What is the primary purpose of method overloading?
- To override superclass methods.
- To extend the functionality of a class.
- To provide multiple entry points to a method.
- To improve code readability.
- Can method overloading be applied to static methods?
- Yes
- No
- It depends on the access modifier of the method.
- Only in interfaces
- How does Java determine which overloaded method to invoke?
- By checking the method signature.
- By checking the return type of the method.
- By checking the method body.
- By checking the method's access modifier.
- What happens if two overloaded methods have the same name and parameter types?
- It results in a compilation error.
- Java selects the method with the lowest accessibility.
- Java selects the method with the highest accessibility.
- Java selects the method declared first in the class.