Adrian
Adrian

Reputation: 20068

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.

Upvotes: 4

Views: 2037

Answers (2)

dr jerry
dr jerry

Reputation: 10026

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.

Upvotes: 2

Vivien Barousse
Vivien Barousse

Reputation: 20875

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.

Upvotes: 10

Related Questions