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.

Invoking One Object Method from Another

As you might expect, it is legal and common to invoke one object method from another. For example, to normalize a complex number, you divide through (both parts) by the absolute value. It may not be obvious why this is useful, but it is.

Let's write the method normalize as an object method, and let's make it a modifier.

  public void normalize () {
    double d = this.abs();
    real = real/d;
    imag = imag/d;

The first line finds the absolute value of the current object by invoking abs on the current object. In this case I named the current object explicitly, but I could have left it out. If you invoke one object method within another, Java assumes that you are invoking it on the current object.

As an exercise, rewrite normalize as a pure function. Then rewrite it as a class method.

Last Update: 2011-01-24