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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With