CS 46B - Lecture 2

Cover page image

Cay S. Horstmann

Pre-class reading

Inner Class

Example: Comparator

Anonymous Classes

Lecture 2 Clicker Question 1

Let's make Item an inner class of ArrayListAddressBook (from the lab):

public class ArrayListAddressBook 
{
   private class Item 
   {
      String name;
      String key;
      String value;
   }
   ...
}

Which of the following is true?

  1. All methods of the ArrayListAddressBook class can construct and access Item objects
  2. Any code outside the ArrayListAddressBook class refers to the inner class as ArrayListAddressBook.Item
  3. The Item class is poorly designed because the instance variables of Item should have been declared as private
  4. The Item class should have been added to the AddressBook interface instead of the ArrayListAddressBook class

Mock Objects

Lecture 2 Clicker Question 2

Why is it necessary that the real class and the mock address book class implement the same interface?

  1. In order to make use of already-written methods in Java classes such as Arrays and Collections
  2. In order to minimize the amount of code that needs to be updated when the mock class is replaced with the real class
  3. In order to allow two programmers to work independently on each class
  4. In order to reuse the address book class in other projects

Interfaces in the Wild

Worked Example: Sequences

Lecture 2 Clicker Question 3

public class Mystery implements Sequence
{
   private Sequence sequence;
   public Mystery(Sequence sequence) { this.sequence = sequence; }
   public int next() { return sequence.next() % 10; }
}

Which of the following is true?

  1. It is not legal for a class to implement an interface and have an instance variable of the same interface.
  2. If one makes a Mystery object and calls next on it, then an infinite recursion occurs, i.e. the next method keeps calling itself
  3. The process method can be rewritten as
    public void process(Sequence seq, int valuesToProcess)
    {
       Sequence digits = new Mystery(seq);
       for (int i = 1; i <= valuesToProcess; i++) { counters[digits.next()]++; }
    }
  4. The loop
    Sequence seq = new Mystery(new SquareSequence());
    for (int i = 1; i <= 5; i++) System.out.print(seq.next());

    prints 1491625

Lab

???