开发者

Implement interface methods that do nothing

开发者 https://www.devze.com 2023-03-27 09:42 出处:网络
Lets say I have this interface and class: interface IListener { void f(); void g(); 开发者_Python百科void h();

Lets say I have this interface and class:

interface IListener
{
   void f();
   void g();
 开发者_Python百科  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.


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号