Skip to content

Things I like about Java: Anonymous classes

Everybody that knows me in real life knows that my favourite jokes are always those about Java being slow and bloated. But still, in all fairness, Java has some good things.

One of them, rendered obsolete by Java 8’s Lambda Expressions, that I always liked and that I really wish was possible in Swift, is Anonymous classes.

The way I see it, an anonymous class is just a syntax shortcut to declare and instantiate, inline, an instance of a specific interface. It is a quick way to create lightweight objects at the moment they are going to be used, or passed to another object.

Anonymous classes have access to the members of its enclosing class, and local variables in its enclosing class marked as final, which makes them great candidates to be used, in particular, to declare callbacks in particular.

To me, their greatest advantage is that anonymous classes allow you to encapsulate behaviour in a way that you only declare implicit types when you expect to actually reuse them.

Still, Lambda Expressions, similar if not equal to what in Swift we know as closures, might make code more concise in some situations. So, as usual, it comes down to knowing your tools, and careful considering which tool is the best for the job.

Updated on Sept 24th.

Joe Fabisevich points out that something similar to what the sample code does could be achieved in Swift by typealias-ing a closure, and typing AThing’s doAThing parameter as said typealias.

Which is quite similar to a solution based on Java lambdas.

If we need to declare more than one method in the Command interface, though, this approach would fall sort.

Joe also suggests another option in Swift:

This still requires making a type, but it is (or can be) private to the Main class, which in a way achieves the same goal as an anonymous class. It would be a concrete type, yes, but known only to the type enclosing it.

 

Be First to Comment

Leave a Reply

Your email address will not be published. Required fields are marked *