The Java Course provides a general introduction to programming in Java. It is based on A.B. Downey's book, How to Think Like a Computer Scientist. Click here for details.


Overloading

In the previous section you might have noticed that fred and area perform similar functions---finding the area of a circle---but take different parameters. For area, we have to provide the radius; for fred we provide two points.

If two methods do the same thing, it is natural to give them the same name. In other words, it would make more sense if fred were called area.

Having more than one method with the same name, which is called overloading, is legal in Java as long as each version takes different parameters. So we can go ahead and rename fred:

  public static double area
               (double x1, double y1, double x2, double y2) {
    return area (distance (xc, yc, xp, yp));
  }

When you invoke an overloaded method, Java knows which version you want by looking at the arguments that you provide. If you write:

    double x = area (3.0);

Java goes looking for a method named area that takes a single double as an argument, and so it uses the first version, which interprets the argument as a radius. If you write:

    double x = area (1.0, 2.0, 4.0, 6.0);

Java uses the second version of area. More amazing still, the second version of area actually invokes the first.

Many of the built-in Java commands are overloaded, meaning that there are different versions that accept different numbers or types of parameters. For example, there are versions of print and println that accept a single parameter of any type. In the Math class, there is a version of abs that works on doubles, and there is also a version for ints.

Although overloading is a useful feature, it should be used with caution. You might get yourself nicely confused if you are trying to debug one version of a method while accidently invoking a different one.

Actually, that reminds me of one of the cardinal rules of debugging: make sure that the version of the program you are looking at is the version of the program that is running! Some time you may find yourself making one change after another in your program, and seeing the same thing every time you run it. This is a warning sign that for one reason or another you are not running the version of the program you think you are. To check, stick in a print statement (it doesn't matter what you print) and make sure the behavior of the program changes accordingly.



Last Update: 2011-01-24