Interface vs Inheritance

Monkey Forums/Monkey Programming/Interface vs Inheritance

slenkar(Posted 2011) [#1]
Inheritance works well for a gui system, each gui gadget needs to know whether the mouse is over itself, so the super class takes care of that,

So you dont have to re-write point-in-rect for every gadget you create.

Can anyone think of an example where Interfaces work better than Inheritance?

Im not trying to slam Interfaces , Im just curious as to what they are used for.

I suppose one thing could be damaging a unit in a game,
Instead of making every Unit Inherit the 'damagable' class you could simply write an interface.


ziggy(Posted 2011) [#2]
Interfaces are usually good to add standarized functionality to classes.

For example, if you create a sorting algorithm that can work on any "sortable" element, instead of trying to make all sortable classes inherited from a base sortable one, you can just provide the Sortable interface and then, anything implementing it, can be "sorted" using your algorith.


Hima(Posted 2011) [#3]
Many design patterns are possible because of interface. You should check that out :O

Anyway, I think the topic's title is kinda misleading. Interface and Inheritance are created to solve different problems. And from what you're saying, it seems like you want to know more about what's the use of interface more than what's the benefit of it over inheritance.


slenkar(Posted 2011) [#4]
yes true I suppose,


muddy_shoes(Posted 2011) [#5]
It's not a matter of interfaces working "better" than inheritance -- interfaces provide an alternative type of inheritance. Their primary use is to define behaviours or capabilities. Classes can then state that they support these interfaces. As classes can implement multiple interfaces they are inherently more flexible than straight inheritance and allow separate inheritance hierarchies to share common features.

To take your GUI example: yes, it is possible to build a UI system that only uses rects and only ever requires one hit detector method declared at the root but interfaces don't stop you doing that. What interfaces allow you to do is talk about the capability of being "clickable" as separate from being "drawable" or "draggable" or "resizable" etc.

Interface IClickable
    Method Click:Bool( x:Int, y:Int )
End


So, you just create your interface and then you're free to write your top-level point-in-rect implementation. The bonus is that you get to write the UI code that handles clicking based entirely around the IClickable interface. So, if somewhere down the line you want to add circular buttons or bitmap mask buttons or just some quick debug element to catch clicks, you can do so by simply implementing just the IClickable interface and you possibly avoid having to shuffle your existing code around to support it.