ScribblesTopKeyboard input - the endRecursive Data Structures

Recursive Data Structures

Let's next look at the case of building interesting pictures using recursion. Our first project will be to draw targets. We will look at this process recursively. A small target simply consists of a center filled circle or bulleye. A large target consists of an outer ring with a slightly smaller target inside.

See BullsEyeController

While you could probably figure out how to draw this with a while loop, you do not yet know how to keep track of all of the pieces so they can be dragged around. (Later we will see how to do this with arrays.)

Instead our solution involved defining an interface (TargetInterface) and two classes that implement it: BullsEye (representing the simplest target) and RingedTarget, representing targets that consist of rings as well as the center. RingedTarget represents a recursive data structure because it has an instance variable with the same type (interface) that the whole class implements.

We talked in class about how to think about recursion:

  1. Define an interface with all of the methods that both base case and recursive case classes must implement.
  2. Define one or more classes representing base cases. Make sure that all methods from the interface are implemented. Convince yourself that the constructors and methods work correctly.
  3. Define the constructors for recursive classes. Recursive calls of the constructor should only create objects that are simpler than the one being built by the constructor. Similarly, instance variables whose types are either the interface or class should only refer to objects simpler than the one being constructed. In particular, the construction of simpler objects in the constructor body should eventually end up at a base case. Convince yourself that the constructor will be correct under the assumption that the construction of simpler objects is correct.
  4. Write each method under the assumption that it works correctly on all simpler objects. Convince yourself that the methods will be correct under the assumption that instance variables hold simpler objects.

ScribblesTopKeyboard input - the endRecursive Data Structures