Java Reference
In-Depth Information
Listing 2-8. An Anonymous Class Example
// HelloAnonymous.java
package com.jdojo.innerclasses;
public class HelloAnonymous {
public static void main(String[] args) {
new Object() {
// An instance initializer
{
System.out.println ("Hello from an anonymous class.");
}
}; // A semi-colon is necessary to end the statement
}
}
Hello from an anonymous class.
Since an anonymous inner class is the same as a local class without a class name, you can also implement the
examples in Listing 2-3 and Listing 2-4 by replacing the local inner classes with anonymous inner classes. Listing 2-9
rewrites the code for the TitleList class to use an anonymous class. You will notice the difference in the syntax inside
the titleIterator() method shown in Listing 2-3 and Listing 2-9. When using an anonymous class, it is important
to indent the code properly for better readability. You can test the TitleListWithInnerClass by replacing TitleList
with TitleListWithInnerClass in Listing 2-4 and you will get the same output.
Listing 2-9. The TitleList Class Rewritten Using an Anonymous Class as TitleListWithInnerClass
// TitleListWithInnerClass.java
package com.jdojo.innerclasses;
import java.util.ArrayList;
import java.util.Iterator;
public class TitleListWithInnerClass {
private ArrayList<String> titleList = new ArrayList<>();
public void addTitle (String title) {
titleList.add(title);
}
public void removeTitle(String title) {
titleList.remove(title);
}
public Iterator<String> titleIterator() {
// An anonymous class
Iterator<String> iterator =
new Iterator<String> () {
int count = 0;
Search WWH ::




Custom Search