CS1150 (Fall 2012, Section 4): Programming Assignment 12

Interfaces and Abstract Classes


  1. Look up the Java documentation for the Iterable and Iterator interfaces. One convention in Java is that a collection class acts as its own iterator, meaning that ArrayList (for instance) implements both interfaces. Let's do the same thing to Fleet.

    It should be immediately obvious what methods need to be defined for Fleet to implement each interface. For Iterable, we need to implement a single method called iterator that returns an Iterator<E>. The <E> is something called a generic, which you will learn about later. For now, replace the E with Car and define your iterator method as returning an Iterator. This method should set a counter representing the ``current'' index into the array of Cars to 0 (resetting the iterator) and return this.

    For Iterator, we must implement two methods (the third is optional): hasNext, which simply indicates if there are any other elements; and next, which actually gets the next element (E; don't worry that you have never seen a type called E, instead give this method a return type of Car) by returning the element in the array of Cars at the index indicated by the counter (see bottom of previous paragraph) and incrementing this index.
  2. Modify the Fleet class so that it implements the two interfaces by adding
    implements Iterable, Iterator
    to the class definition. Implement the appropriate methods as described above. Wherever you see E, replace it with Car. Generics are a useful and interesting topic, but beyond the scope of this assignment.
  3. Test your implementation by using a for (Car car : fleet) structure to sequentially print the descriptions of each Car. This should be an option from the main menu (e.g.: "Enter 'PRINT' to print the fleet"). Use helper methods if/when appropriate.


Submit as per the syllabus.