Algorithms and OOD (CSC 207 2014F) : Labs

Laboratory: Anonymous Inner Classes


Summary: We begin our explorations of Java's anonymous inner classes, classes without explicit names (hence, “anonymous”) that are declared within other classes (hence, “inner”).

Prerequisite Knowledge: Classes, Interfaces, Interitance, Iterators, Predicates

Preparation

Fork and clone the repository at https://github.com/Grinnell-CSC207/anonymous-inner-classes.

Exercises

Exercise 1: Exploring the Basics

a. Read the descriptions of Greeter.java and Greetable.java to make sure that you understand the purposes and components of each interface.

b. Read through GreetableExperiments.java so that you can see the shape of the basic experiment.

c. Look at SampleGreetable1.java and predict what the output of the experiment will be. Check your prediction.

d. Look at SampleGreetable2.java. Update the experiment to use SampleGreetable2. Predict the output. Then check your prediction.

e. Look at SampleGreetable3.java. Update the experiment to use SampleGreetable3. Predict the output. Then check your prediction.

f. Look at SampleGreetable4.java. Update the experiment to use SampleGreetable4. Predict the output. Then check your prediction.

g. Change the body of GreetableExperiments.main to read

Greetable g = new SampleGreetable4();
experiment(g);
experiment(g);

What do you expect the new output to be? Check your prediction.

h. Look at SampleGreetable5.java. Update the experiment to use SampleGreetable5. Predict the output. Then check your prediction.

i. Look at SampleGreetable6.java. Update the experiment to use SampleGreetable6. Predict the output. Then check your prediction.

Exercise 2: Named Greetables

Design and implement a class that implements the Greetable interface. Your class should have a field of type String called name that gets filled in by the constructor. The objects that your greeter method returns should incorporate the name in their output, but each should give independent output.

Exercise 3: Updating Greeter Output

Create a new class, based on SampleGreetable4, in which the Greeter returned by greeter has an internal field i that gets printed and updated each time the greet method is called. The output should be something like:

Greeting 2 from greeter 3 of 5.

Exercise 4: Fun with Filtering

a. Read through the code of PredicateExample.java. Predict what its output will be.

b. Run PredicateExample to check your prediction.

c. Update PredicateExample.java so that it prints out all of the words in the array that end in “e”.

Exercise 5: Configurable Filtering

Extend PredicateExample so that it prompts the user for a string and prints out all of the elements of our array that contain that string.