Incremental Java
Overloading Methods

What is Overloading?

For convenience, Java allows you to write more than one method in the same class definition with the same name.

For example, you can have two methods in ShoppingCart class named computeCost.

Having two or more methods named the same in the same class is called overloading. It's not overloading if you have the same method name in two different classes.

There's a rule for overloading

Two methods may share the same name, provided the number of parameters are different, or if they both have the same parameters, then there is at least one position, i where the parameter types differ.
If the parameter lists of both methods (with the same name) have the same number of parameters and the types of the parameters match, then you have a problem. Java won't let you overload in this way. That's because Java needs to know which method to call, and it can't tell which.

If you differ in parameters, Java can easily tell which version you want.

public int computeCost() ;
public int computeCost( int tax ) ;
These two methods could exist in the same class since the parameter list.

The following could not:

public int computeCost( int surcharge, boolean addSurcharge ) ;
public int computeCost( int tax, boolean getDiscount ) ;
These two have identical number of parameters, and the types are the same. The Java compiler doesn't care what the parameter names are. It just sees the types of the parameter list as ( int, boolean ).

The following is also not valid:

public int computeCost( int tax ) ;
public boolean computeCost( int tax ) ;
The parameter lists are identical in type and number. It doesn't matter that the return type is not the same.

Why Overload?

Sometimes you have a method name that is exactly what you want. For example, we have computeCost() with no parameters. Maybe this computes a cost with a default tax. However, computeCost( int tax ) computers the cost with a tax specified by an argument. Is there a reason to have to come up with a new name?

Java says no.

Thus, Java support overloading.