Question

This is from an article from oracle about anonymous classes I was reading:

Anonymous classes are ideal if you have to implement an interface that contains two or more methods

I though that is ideal if you have to implement fewer than two methods, cause you don't need to make more concrete named classes, but if you have to implement more than two will be more unreadable.

My question is: Why should implementing anonymous classes with 2 or more methods be ideal?

Was it helpful?

Solution

You took that sentence out of context. Look at the sentence immediately before that one:

Because the EventHandler<ActionEvent> interface contains only one method, you can use a lambda expression instead of an anonymous class expression. See the section Lambda Expressions for more information.

(emphasis by me)

You'll be able to use lambda expression instead of anonymous classes with only a single method in the future, so using an anonymous class only makes sense if your interface has more than one method.

Readability might suffer if it has many methods, but there is no other language construct that enforces that a specific implementation may only be used at one point in the code.

OTHER TIPS

The article is including information from JDK 8, in which case Lambda expressions can be used to implement single function interfaces instead of having to use an anonymous class.

So the 2+ method suggestion is strictly for JDK 8, for 7 and below anonymous classes are the only way (well, outside of full classes) for single method and multiple method interface implementations.

This is probably taking into account the new concise syntax available in Java 8 (fingers crossed) for single-method interfaces (i.e. Lambda Expressions). That would provide a better option than anonymous classes if the interface does indeed only have a single method.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top