Default implementations in inherited interfaces

Saurabh Das via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Thu Jul 21 06:37:30 PDT 2016


On Thursday, 21 July 2016 at 12:42:14 UTC, Adam D. Ruppe wrote:
> On Thursday, 21 July 2016 at 09:41:27 UTC, Saurabh Das wrote:
>> I have an interface A which declares a certain function. A 
>> second interface B inherits from A and wishes to provide a 
>> default implementation for that function.
>
> You can't, interfaces cannot have implementations of virtual 
> functions. Your code is trying to define two separate functions 
> with the same name (the compiler should probably prohibit that, 
> since it doesn't do want you want it to do).
>
> Your best bet is to make B an abstract class instead of an 
> interface. Then it can override interface functions. Of course, 
> it will also tie you down as you can only inherit from one 
> class, but it will actually work.

I see.

Java 8 has a 'default' keyword that allows interfaces to provide 
a default implementation and sub-classes can optionally override 
it if needed. The rationale behind it was extending interfaces 
without causing old code to faill. (called "virtual extension 
methods" or "defender methods"). The use case is similar to above.

Is there a way to achieve an equivalent functionality in D?

Thanks,
Saurabh



More information about the Digitalmars-d-learn mailing list