Method overloading

There can be several methods with the same name that differ in the number or types of arguments. Then one speaks of method overloading.

The purpose of this concept is to give semantically similar actions on different data types the same name.

Overloading often occurs with constructors or conversion methods. For an overload to be performed, at least one of the following conditions must be met:

  • The data type of at least one passing parameter is different from the other methods with the same name.
  • The number of passing parameters is different.

Method Overloading

class MethodOverloading {

	static int add(int a, int b) {
		int result = a + b;
		return result;
	}

	static double add(double a, double b) {
		double result = a + b;
		return result;
	}

	public static void main(String[] args) {
		System.out.println("Integer Calculation: " + add(6, 7));
		System.out.println("Double Calculation:  " + add(8.45, 7.23));
	}
}
Output
Integer Calculation 13
Double Calculation 15.68

As just mentioned, overloading methods is often applied to constructors.

The concept of constructor overloading is similar to method overloading, which means that we create more than one constructor for a single class. Constructor overloading is performed to initialize the member variables of the class in different ways.

Example of an overloaded constructor:

Constructor Overloading

public class codevisionz {

  public static class Person {
    String name;
    String prename;

    // Default constructor
    Person() {}

    // 1. overloaded constructor
    Person(String name) {
      this.name = name;
    }

    // 1. overloaded constructor
    Person(String name, String prename) {
      this.name = name;
      this.prename = prename;
    }
  }

  public static void main(String[] args) {
    Person p1 = new Person("John");
    Person p2 = new Person("Doe", "John");

    System.out.println(p1.name);
    System.out.print(p2.prename + " " + p2.name);
  }
}
Output
John
John Doe