Anonymous classes
Theory and problem statement
Machine translation, not yet reviewed by a native speaker.
An anonymous class is a class without a name, declared and created in one place. It's handy when an implementation is needed only once:
interface Greeter {
String greet(String name);
}
Greeter polite = new Greeter() { // "a class that implements Greeter", right here
@Override
public String greet(String name) {
return "Good afternoon, " + name;
}
};
polite.greet("Kai");
"One-off" subclasses of classes are created the same way: new Thread() { public void run() { … } }.
An anonymous class sees the local variables around it — as long as they don't change (effectively final).
For interfaces with a single method there's a shorter form — a lambda (a topic at the end of the course).
Task. Fill the table of operations with anonymous classes that implement Operation: + - * / max
(integer division). The program evaluates expressions like 7 * 6.
Sign up for free to solve this task right in your browser: code editor, running, test checks and hints.