HOME C C++ PYTHON JAVA HTML CSS JAVASCRIPT BOOTSTRAP JQUERY REACT PHP SQL AJAX JSON DATA SCIENCE AI

Method Overloading

With method overloading, multiple methods can have the same name with different parameters:

Example
    
int myMethod(int a)
float myMethod(float a)
double myMethod(double a, double b)

Consider the following example, which has two methods that add numbers of different type:

Example
    
static int plusMethodInt(int a, int b) {
  return a + b;
}

static double plusMethodDouble(double a, double b) {
  return a + b;
}

public static void main(String[] args) {
  int Num1 = plusMethodInt(8, 5);
  double Num2 = plusMethodDouble(4.3, 6.26);
  System.out.println("int: " + Num1);
  System.out.println("double: " + Num2);
}

Instead of defining two methods that should do the same thing, it is better to overload one.

In the example below, we overload the plusMethod method to work for both int and double:

Example
    
static int plusMethod(int a, int b) {
  return a + b;
}

static double plusMethod(double a, double b) {
  return a + b;
}

public static void main(String[] args) {
  int Num1 = plusMethod(8, 5);
  double Num2 = plusMethod(4.3, 6.26);
  System.out.println("int: " + Num1);
  System.out.println("double: " + Num2);
}

Instead of defining two methods that should do the same thing, it is better to overload one.

In the example below, we overload the plusMethod method to work for both int and double:

Example
    
static int plusMethod(int a, int b) {
  return a + b;
}

static double plusMethod(double a, double b) {
  return a + b;
}

public static void main(String[] args) {
  int Num1 = plusMethod(8, 5);
  double Num2 = plusMethod(4.3, 6.26);
  System.out.println("int: " + Num1);
  System.out.println("double: " + Num2);
}