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?
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. Anonymous classes are ideal for implementing an interface that contains two or more methods.
A normal class can implement any number of interfaces but the anonymous inner class can implement only one interface at a time.
Java Anonymous inner class can be created in two ways: Class (may be abstract or concrete). Interface.
Anonymous classes are inner classes with no name.We may either extend an existing class or implement an interface.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With