пятница, 5 января 2024 г.

Method overloading in Java

    Method overloading in Java allows a class to have multiple methods with the same name, but with different parameter lists. It provides a way to define multiple methods within the same class that perform similar tasks but with variations in the type or number of parameters.

Here are the key rules and considerations for method overloading in Java:

  • Method Signature:

Methods must have the same name but different parameter lists. The parameter lists can differ in terms of the number of parameters, types of parameters, or both.

  • Return Type:
The return type of the methods can be the same or different. Method overloading is not based on the return type.

  • Access Modifiers:
Access modifiers (public, private, protected) can be the same or different for overloaded methods.

  • Exceptions:
Method overloading can include methods with different exception types or the same exception types.

public class Calculator {
// Method with two int parameters
public int add(int a, int b) {
return a + b;
}
// Method with three int parameters
public int add(int a, int b, int c) {
return a + b + c;
}
// Method with two double parameters
public double add(double a, double b) {
return a + b;
}
// Method with a different parameter type (String)
public String add(String a, String b) {
return a + b;
}

public static void main(String[] args) {
Calculator calculator = new Calculator();
        // Calls the first method
System.out.println(calculator.add(2, 3));
        // Calls the second method
System.out.println(calculator.add(2, 3, 4));
        // Calls the third method
System.out.println(calculator.add(2.5, 3.5));
        // Calls the fourth method
System.out.println(calculator.add("Hello", "World"));
}
}

Комментариев нет:

Отправить комментарий