How would you use an anonymous class to create a one-off subclass with a customized implementation, distinct from anonymous classes implementing an interface, and what specific syntax quirk applies?
Short answer
An anonymous class can also extend a concrete (or abstract) class rather than implementing an interface, providing an inline, one-off subclass with overridden or additional behavior specific to just that single usage site -- the syntax is `new SuperClass(constructorArgs) { ...
Advertisement
AModel answer
An anonymous class can also extend a concrete (or abstract) class rather than implementing an interface, providing an inline, one-off subclass with overridden or additional behavior specific to just that single usage site -- the syntax is `new SuperClass(constructorArgs) { ... overrides/additions ... }`, distinct from the interface-implementing form only in that constructor arguments can be passed to the superclass's constructor (since there IS an actual superclass constructor being invoked, unlike implementing a pure interface which has no constructor at all).
public abstract class Shape {
abstract double area();
Shape(String name) { System.out.println("Created: " + name); }
}
Shape customShape = new Shape("CustomCircle") { // anonymous SUBCLASS, passing a constructor argument
double radius = 5.0;
@Override
double area() { return Math.PI * radius * radius; }
};
System.out.println(customShape.area());Real-world example
A test suite creates a one-off anonymous subclass of an abstract HttpResponse class specifically to override just the getStatusCode() method for a single specific test case, avoiding the need to define and maintain an entirely separate, permanently-named test-double class file just for that one narrow test scenario.
Likely follow-ups
- Can an anonymous class extending a concrete class add entirely new public methods callable from outside, or are its capabilities limited to what the reference type's static type allows?
- Why can't an anonymous class have an explicit, named constructor of its own?
Related topics