Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implementing anonymous classes for two or more methods

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?

like image 543
nachokk Avatar asked Jul 04 '13 23:07

nachokk


People also ask

Can anonymous class have multiple methods?

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.

Can an anonymous inner class implement multiple interfaces?

A normal class can implement any number of interfaces but the anonymous inner class can implement only one interface at a time.

What are the two ways to create an anonymous inner class?

Java Anonymous inner class can be created in two ways: Class (may be abstract or concrete). Interface.

Can anonymous class implement an interface and extend parent class?

Anonymous classes are inner classes with no name.We may either extend an existing class or implement an interface.


2 Answers

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.

like image 112
jlordo Avatar answered Oct 01 '22 01:10

jlordo


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.

like image 36
Trevor Freeman Avatar answered Oct 01 '22 01:10

Trevor Freeman