EMZETT.
Login

Anonymous Classes

In short: An inner class with no name of its own, defined directly at the spot and immediately instantiated where it’s needed — mostly for one-off, short implementations.

In more detail: Anonymous classes save the effort of creating a full, separately named class for an implementation of an interface or an abstract class that’s only needed once. In modern languages, anonymous classes are increasingly being replaced for simple cases by shorter lambda expressions.

In Depth

The idea behind it: if an implementation of an interface or an abstract class is needed at exactly one single spot in the code and shouldn’t be reused anywhere else, a dedicated, named class type isn’t worth it — you define the class “anonymously” right on the spot, as an expression instead of a separate declaration.

In pseudocode-like notation (close to Java, where this concept is especially common):

button.onClick(new anonymous class implements ClickListener {
    method click() {
        showMessage("Button was clicked")
    }
})

Instead of first declaring a class MyClickListener implements ClickListener { ... } separately and then passing an instance of it, the definition and use are combined into one step. This keeps the code compact at the call site when the logic is genuinely short and one-off.

The downside shows up as soon as the implementation grows: a multi-line, nested anonymous class in the middle of a method call quickly makes the code cluttered (a “pyramid of anonymity”). The rule of thumb is therefore: as long as the implementation stays limited to a few lines (ideally a single method with a short body), a lambda expression is usually the more readable choice today — lambdas were introduced in many languages exactly to replace the boilerplate of anonymous classes for the most common use case (an interface with exactly one method). Anonymous classes remain relevant, though, when several methods have to be implemented or additional state (custom fields) is needed — a single lambda expression can’t represent that.

Access to the surrounding environment

An anonymous class can access variables from its surrounding scope — this is called a closure-like effect, even though an anonymous class isn’t technically a pure closure in the functional sense. A restriction in many languages: the externally captured variable has to be final/immutable or behave like one, since otherwise it wouldn’t be clear which value the anonymous class should see once the variable changes after creation:

final threshold = 100
list.filterWith(new anonymous class implements Filter {
    method matches(element) {
        return element.value > threshold   // access to outer variable, read-only allowed
    }
})

Special case: anonymous classes for immediate extension

Anonymous classes aren’t only used to implement an interface, but also to selectively extend an existing class, without creating a dedicated named subclass for it — for example, to override a method for a single test case:

account = new anonymous class extends Account {
    // override behaviour for exactly this one test
    method calculateInterest() { return 0 }
}

Comparison to other languages

The basic principle “immediately create a nameless instance with its own behaviour” also shows up in a similar form outside classic OOP languages: JavaScript has anonymous function expressions (function() { ... }) and object literals with methods, C# has a comparable but purely data-focused concept with anonymous types (new { Name = "x" }). The common denominator is always the same: something is needed that only exists in one place — so why give it its own, permanent name?

See also: Inner Classes, Lambda, Interface