Default Implementation For an Interface

Jonathan M Davis jmdavisProg at gmx.com
Thu Feb 16 02:23:24 PST 2012


On Thursday, February 16, 2012 11:11:20 Jacob Carlborg wrote:
> You can create an abstract class that implements some parts of the
> interface. Then the user (developer) is free to choose to inherit from
> the interface or the abstract class.

Which results in a classic problem that you run into in Java all the time when 
dealing with event-based programming (since it deals with events via 
interfaces). If you have a class that only really needs to implement a couple 
of the functions from the interface of an event listener, then you can derive 
from the class which implements it and gives them all empty bodies. But if you 
need your class to implement multiple such interfaces, you can only do that 
with one of them, which gets really annoying, because then you have to create 
a bunch of empty method bodies yourself. It's one of the classic examples 
where multiple inheritance would be desirable.

The current situation in D is exactly the same (though, since we don't have a 
swing equivalent, I don't think that it's something that D programmers are 
frequently running into at the moment). AIUI, Java is going to be adding the 
ability to give interfaces default implementations such that that 
implementation is effectively copy-pasted into your class when you implement it 
and don't provide an implementation yourself (rather than the function in your 
class overidding it as would be the case with an abstract class). This nicely 
solves the event listener problem, and D doesn't have that. I assume that 
that's the sort of thing that the OP is looking for.

Now, if you use template mixins, I believe that it's possible to use that to 
mixin default implementations for the functions in an interface, which should 
solve the problem for D. So, that's probably good enough for D without having 
to make it so that interface functions can have default implementations.

- Jonathan M Davis


More information about the Digitalmars-d-learn mailing list