The Advantages & Disadvantages of the Overloading Method in Java
Overloaded methods are methods in the same class that share the same name but accept different variable types as arguments. For example, a class may contain two different "add" methods: one that accepts two double values, "add(double a, double b)," and one that accepts two integer values, "add(int a, int b)." The computer automatically decides which method to call at run-time based on the variable types being passed to the method.
Overloaded methods give programmers the flexibility to call a similar method for different types of data. If you are working on a mathematics program, for example, you could use overloading to create several "multiply" classes, each of which multiplies a different number of type of argument: the simplest "multiply(int a, int b)" multiplies two integers; the more complicated method "multiply(double a, int b, int c)" multiplies one double by two integers -- you could then call "multiply" on any combination of variables that you created an overloaded method for and receive the proper result.
Overloading is also used on constructors to create new objects given different amounts of data. For example, you could use overloading to create three different constructors for a "House" object with a house number, street name and color variables. The simplest constructor "House()" takes no arguments and creates a house with default or empty variables. A more complex constructor, "House(int houseNumber, String streetName)," creates a house with the specified house number and street name, but a default or empty color. The most complex constructor, "House(int houseNumber, String streetName, String color)," creates a house with all of the specified information, leaving nothing as default. You could then create a house object based on the information currently available, with the unavailable information left blank or at default.
Overloaded methods must use different numbers or types of arguments to avoid ambiguity. If you create two methods in the same class that have the same name and accept two integers as arguments, the Java compiler will be unable to distinguish between the two, even if the input variables have different names. For example, the method "add(int a, int b)" cannot exist in the same class as the method "add(int c, int d)."
You must define a return type for each overloaded method. Methods can have different return types -- for example, "add(int a, int b)" may return an integer, while "add(double a, double b)" returns a double. However, Java cannot distinguish between two different methods based on their return type. Therefore, "int multiply(double a, double b)" cannot exist in the same class as "double multiply(double a, double b)."