CS 46B - Lecture 3

Cover page image

Cay S. Horstmann

Pre-class reading

Plagiarism and Cheating

Interface

Lecture 3 Clicker Question 1

Which objects can be passed to the pay method in the preceding slide?

Click all that apply

  1. Instances of Customer
  2. Instances of Cat
  3. Instances of Person
  4. Instances of Object

Lecture 3 Clicker Question 2

Which service does this stand mixer provide to any attachment that conforms to the “interface” for plugging in attachments?

  1. Mixing ingredients
  2. Whipping a liquid such as cream or mayonnaise
  3. Rotating the attachment
  4. All of the above

Measurable Interface

Decoupling

Lecture 3 Clicker Question 3

In Eclipse, make a project out of the ch10/section_1 directory of the Book Code. Add the class below, and add the print statement to the main method of the tester.

public class Word implements Measurable
{
   private String text;
   public Word(String text) { this.text = text; }
   public double getMeasure() { return text.length(); }
}
...
System.out.println(Data.average(new Word[] {
   new Word("Hello"), new Word("World!") }));

How should the tester be completed?

  1. System.out.println("Expected: 5");
  2. System.out.println("Expected: 5.5");
  3. System.out.println("Expected: 6");
  4. System.out.println("Expected: Hello, World!");

Interface Variables

Casts

Worked Example: Number Sequences

Sequence Classes

Lecture 3 Clicker Question 5

Make an Eclipse project from the ch10/worked_example_1 directory in the Book Code

What are the last digits of the sequence of the cubes? (13, 23, 33, etc.?)

Implement the sequence class and modify the SequenceDemo program.

What result do you get?

  1. 100 100 100 100 100 100 100 100 100 100
  2. 100 200 0 0 200 100 200 0 0 200
  3. 105 94 81 112 89 103 103 100 108 105
  4. Something else

Lecture 3 Clicker Question 6

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

Before Next Class