Java Reference
In-Depth Information
Introduction to Algorithms (Cormen, Leiserson, and Rivest 1990) says: "An algorithm is any
well-defined computational procedure that takes some value, or set of values, as input and
produces some value, or set of values, as output" (p. 1).
An algorithm is a procedure—a sequence of instructions—that accepts inputs and produces
output. In this regard, an algorithm is similar to a method. A method accepts inputs—its
parameter list—and produces an output—its return value. However, many algorithms require
more than one method to execute in an object-oriented program. For example, the isTree()
algorithm in Chapter 5, Composite, requires four methods, as Figure 20.1 shows.
Figure 20.1. Four isTree() methods collaborate to effect the algorithm for determining
whether an instance of MachineComponent is a tree.
CHALLENGE 20.2
How many algorithms, operations, and methods does Figure 20.1 depict?
Algorithms get something done. They may appear as part of a method, or they may involve
many methods. Algorithms that require more than one method often rely on polymorphism to
allow multiple implementations of a single operation. Polymorphism is the principle that
method invocation depends on both the operation invoked and the class of the invocation
receiver.
For example, you might ask which method executes when Java encounters the expression
m.isTree() . The answer is, it depends. If m is an instance of Machine , Java will invoke
Machine.isTree() . If m is an instance of MachineComposite , Java will invoke
MachineComposite.isTree() . Informally, polymorphism means that the right method
gets invoked for the right type of object. Many patterns use polymorphism, which in some
cases ties directly to the intent of the pattern. But before we investigate those patterns, it is a
good idea to have a solid understanding of the mechanics of Java methods.
Search WWH ::




Custom Search