Home Python C Language C ++ HTML 5 CSS Javascript Java Kotlin SQL DJango Bootstrap React.js R C# PHP ASP.Net Numpy Dart Pandas Digital Marketing

Overloading


Java Method Overloading

Method overloading in Java allows you to define multiple methods in the same class with the same name but with different parameter lists. This provides flexibility and improves code readability by allowing you to use the same method name for different behaviors based on the parameters passed. The methods must have different parameter types or a different number of parameters. Here's an overview of method overloading in Java:

Example

        public class Calculator {
            // Method to add two integers
            public int add(int a, int b) {
                return a + b;
            }
            
            // Method to add three integers
            public int add(int a, int b, int c) {
                return a + b + c;
            }
            
            // Method to add two doubles
            public double add(double a, double b) {
                return a + b;
            }
        }
      

Calling Overloaded Methods

The appropriate method is automatically chosen based on the number and type of arguments passed during the method call.

Calculator calculator = new Calculator();
int sum1 = calculator.add(5, 3);            // Calls the first add method (int version)
int sum2 = calculator.add(5, 3, 2);         // Calls the second add method (int version)
double sum3 = calculator.add(2.5, 3.7);  // Calls the third add method (double version)
      

Rules for Method Overloading

  1. Methods must have the same name.
  2. Methods must have a different number of parameters.
  3. Methods must have different types of parameters (primitive types, reference types, varargs).
  4. Methods can have different return types, but overloading based solely on return type is not allowed (the compiler won't be able to distinguish which method to call based on return type).

Benefits of Method Overloading

  1. Enhanced readability: Using the same method name for similar behaviors improves code readability.
  2. Reduced code duplication: Avoids redundancy by consolidating similar behaviors into a single method name.
  3. Flexibility: Allows for more intuitive method names, as you don't have to invent new names for similar functionalities.

Overloading vs. Overriding



Advertisement





Q3 Schools : India


Online Complier

HTML 5

Python

java

C++

C

JavaScript

Website Development

HTML

CSS

JavaScript

Python

SQL

Campus Learning

C

C#

java