Java Reference
In-Depth Information
String msg = (args.length == 1) ? args[0] : "noth-
ing to say";
@Override
public void speak()
{
System.out.println(msg);
}
}
.speak();
}
}
Listing 3-11
is very similar to
Listing 3-10
.
However, instead of subclassing a
Speaker
class,thislisting'sanonymousclassimplementsaninterfacenamed
Speak-
able
. Apart from the
<init>()
method calling
java.lang.Object()
(inter-
faces have no constructors),
Listing 3-11
behaves like
Listing 3-10
.
Although an anonymous class does not have a constructor, you can provide an in-
stance initializer to handle complex initialization. For example,
new Office()
{{addEmployee(new Employee("John Doe"));}};
instantiates an an-
onymoussubclassof
Office
andaddsone
Employee
objecttothisinstancebycall-
ing
Office
's
addEmployee()
method.
You will often find yourself creating and instantiating anonymous classes for their
convenience.Forexample,supposeyouneedtoreturnalistofallfilenameshavingthe
“
.java
”suffix.Thefollowingexampleshowsyouhowananonymousclasssimplifies
using the
java.io
package's
File
and
FilenameFilter
classes to achieve this
objective:
String[] list = new File(directory).list(new FilenameFil-
ter()
{
@Override
public boolean accept(File f, String s)
{
return s.endsWith(".java");
}
});