July 10, 2008

Chapter: Inner Classes

Create an interface U with three methods. Create a class A with a method that produces a reference to a U by building an anonymous inner class. Create a second class B that contains an array of U. B should have one method that accepts and stores a reference to a U in the array, a second method that sets a reference in the array (specified by the method argument) to null, and a third method that moves through the array and calls the methods in U. In main(), create a group of A objects and a single B. Fill the B with U references produced by the A objects. Use the B to call back into all the A objects. Remove some of the U references from the B.

I also added a couple lines of code to show that A's inner class has access to it's private methods.

package chapter.innerClasses;

interface U {
void one();
void two();
void three();

class A {
U getU() {
return new U() {
public void one() {System.out.println("one");}
public void two() {System.out.println("two");}
public void three() {System.out.println("three"); printSomething();}

private void printSomething() {System.out.println("Something");}

class B {
private U[] arrayOfU = new U[10];
private int position = 0;

public void storeU(U U_Reference) {
if (position < 10 && position >= 0)
arrayOfU[position++] = U_Reference;

public void setNull(int index) {
if (index < 10 && index >= 0)
arrayOfU[index] = null;

public void callU() {
for (U myU : arrayOfU) {
if (myU != null) {

public class Excercise23 {
public static void main(String[] args) {
A firstA = new A(), secondA = new A();
B theB = new B();