Introduce Java Method Overloading and give examples
Method overloading in Java is a feature that allows a class to have more than one method with the same name, but with different parameter lists. This means that you can define multiple methods with the same name as long as they have different types, numbers, or order of parameters. Method overloading is a way to achieve polymorphism in Java.
Here are some examples to illustrate method overloading in Java:
class MathOperations {
// Method to add two integers
int add(int a, int b) {
return a + b;
}
// Method to add three integers
int add(int a, int b, int c) {
return a + b + c;
}
// Method to add two double values
double add(double a, double b) {
return a + b;
}
}
public class Main {
public static void main(String[] args) {
MathOperations math = new MathOperations();
System.out.println("Sum of 2 and 3: " + math.add(2, 3)); // Calls the first method
System.out.println("Sum of 2, 3 and 4: " + math.add(2, 3, 4)); // Calls the second method
System.out.println("Sum of 2.5 and 3.5: " + math.add(2.5, 3.5)); // Calls the third method
}
}
class Display {
// Method to display an integer
void show(int a) {
System.out.println("Integer: " + a);
}
// Method to display a string
void show(String b) {
System.out.println("String: " + b);
}
// Method to display a double
void show(double c) {
System.out.println("Double: " + c);
}
}
public class Main {
public static void main(String[] args) {
Display display = new Display();
display.show(10); // Calls the integer method
display.show("Hello"); // Calls the string method
display.show(10.5); // Calls the double method
}
}
class Concatenator {
// Method to concatenate two strings
String concatenate(String a, String b) {
return a + b;
}
// Method to concatenate three strings
String concatenate(String a, String b, String c) {
return a + b + c;
}
}
public class Main {
public static void main(String[] args) {
Concatenator concat = new Concatenator();
System.out.println(concat.concatenate("Hello, ", "World!")); // Calls the first method
System.out.println(concat.concatenate("Java ", "is ", "fun!")); // Calls the second method
}
}
Method overloading is a powerful feature in Java that enhances code readability and reusability. By allowing multiple methods with the same name but different parameters, developers can create more intuitive and flexible APIs.