Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implement interface methods that do nothing

Lets say 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 taken from Design Patterns Java Workbook.

like image 746
Adrian Avatar asked Dec 17 '22 10:12

Adrian


2 Answers

The aim is to makes the implementation of the interface easier if you don't need all the methods. You can extend the adapter and override only the methods you want to. These classes only exist for convenience.

For example, in Swing, when implementing a MouseListener, you might not want to treat all the mouse events. In this case, you can extends MouseAdapter and treat only the events you are interested in.

Please note that the Adapter class usually implements the interface as well.

like image 106
Vivien Barousse Avatar answered Dec 18 '22 23:12

Vivien Barousse


In the example you posted it is useless, however if you make adapter to implement IListener (class Adapter implements IListener), it becomes a bit more usefull as you can than instantiate an Adaptor object like new Adapter();

Otherwise Adapter would remain an abstract class which cant be instantiated nor its children until all the methods defined in the interface have a proper implementation. An empty implementation being also a proper implementation.

like image 27
dr jerry Avatar answered Dec 18 '22 23:12

dr jerry