Java Reference
In-Depth Information
@Override
public boolean hasNext() {
return (count < titleList.size());
}
@Override
public String next() {
return titleList.get(count++);
}
}; // Anonymous inner class ends here
return iterator;
}
}
The
titleIterator()
method of
TitleListWithInnerClass
has two statements. The first statement creates
an object of an anonymous class and stores the object's reference in the
iterator
variable. The second statement
returns the object reference stored in the
iterator
variable. In such cases, you can combine the two statements
into one statement. The
getRandomInteger()
method shown in Listing 2-5 can be rewritten using an anonymous
class as follows:
public RandomInteger getRandomInteger() {
// Anonymous inner class that inherits the RandomInteger class
return new RandomInteger() {
public int getValue() {
// Get two random integers and return
// the average ignoring the fraction part
long n1 = rand.nextInt();
long n2 = rand.nextInt();
int value = (int)((n1 + n2)/2);
return value;
}
};
}
A static Member Class Is Not an Inner Class
A member class defined within the body of another class may be declared
static
. The following snippet of code
declares a top-level class
A
and a
static
member class
B
:
package com.jdojo.innerclasses;
public class A {
// Static member class
public static class B {
// Body for class B goes here
}
}