next up previous
Next: Second Attempt: Dedicated Methods. Up: Why Visitors? Previous: Why Visitors?

First Attempt: Instanceof and Type Casts.

The first attempt may be a loop which uses instanceof to check if a given List-object is a Nil-object or a Cons-object. If it is a Cons-object, then the fields are accessed via type casts, and the loop is repeated.

    List l;      // The List-object we are working on.
    int sum = 0; // Contains the sum after the loop.
    boolean proceed = true;
    while (proceed) {
      if (l instanceof Nil)
         proceed = false;
      else if (l instanceof Cons) {
         sum = sum + ((Cons) l).head; // Type cast!
         l = ((Cons) l).tail;         // Type cast!

The advantage of this code is that it can be written without touching the classes Nil and Cons. The drawback is that the code constantly uses type casts and instanceof to determine what class of object it is considering.

Jens Palsberg