Introduce interface methods that do nothing

Lets say that I have this interface and class:

interface IListener { void f(); void g(); void h(); } class Adapter implements IListener { void f() {} void g() {} void h() {} } 

What is the point of implementing thoose interface methods if they do nothing?

Question from Sample Java Workbook Templates .

+4
source share
2 answers

The goal is to simplify the implementation of the interface if you do not need all the methods. You can extend the adapter and override only the methods you want. These classes exist for convenience only.

For example, in Swing, when implementing MouseListener you may not need to handle all mouse events. In this case, you can expand the MouseAdapter and consider only those events that interest you.

Note that the Adapter class typically implements the interface.

+9
source

In the above example, this is useless, however if you create an adapter to implement IListener ( class Adapter implements IListener ), it becomes a little more useful than you can than create an instance of the Adapter object, for example new Adapter() ;

Otherwise, the Adapter will remain an abstract class that cannot be created, or its children, until all methods defined in the interface have the correct implementation. An empty implementation is also a valid implementation.

+2
source

All Articles