Java programming: anonymous class
The tutor brings up a beloved feature of Java: the anonymous class.
Reading about Java, or reading Java code, you might often encounter an anonymous class. It’s a class that is created with the new operator, but not given a name. Often, one of its methods is called simultaneously – the very reason for its creation:
new Aclass().methodNeeded();
Here’s an example. First, the code for the class that will be called anonymously:
class Anon0{
public void reply(){
System.out.println(“Yes, I’m here.”);
}
}
Now, the application class (the one with the main() method):
class Driver{
public static void main(String[] args){
new Anon0().reply();
}
}
After compiling and running (see how in my article here), you are hopefully rewarded with the greeting, from the anonymous class,
Yes, I’m here.
Hopefully you can have some fun with anonymous classes:)
Source:
Niemeyer, Patrick and Jonathan Knudsen. Learning Java, third ed. Sebastopol: O’Reilly Media, Inc., 2005.
Jack of Oracle Tutoring by Jack and Diane, Campbell River, BC.