The Freya Programming Language

Implementing an interface

See also

Since interfaces are abstract types, without an implementation, they must be implemented by classes or records sooner or later.

The interface list

The inheritance clause from a class or record declaration may list one or more interface types, after the base class reference, if any:

Control = class(Component, IDropTarget, ISynchronizeInvoke,
    IWin32Window, IBindableComponent, IComponent, IDisposable)
    // ...
end;

If the class directly inherits from System.Object, you can omit the base class and, in that case, all types mentioned in the implemented interface list are interface types:

List = class[T](IList[T], ICollection[T], 
    IEnumerable[T], IList, ICollection, IEnumerable)
    // ...
end;

As the last example shows, interfaces in the implementation list may use generic type arguments from the class or record declaration.

Implicit implementation

Now, your class or record must provide methods, properties and events to implement all interface members. The easiest way is to define members with the same name and signature as those defined by the interface type. Suppose you have to create an implementation for the IDisposable interface:

IDisposable = interface
    method Dispose;
end;

The following class implements IDisposable using an implicit implementation:

MyClass = class(IDisposable)
public
    method Dispose;
end;

implementation for MyClass is

    method Dispose;
    begin
        // Whatever...
    end;

Methods, properties and events used in an implicit implementation must be declared public.

Explicit implementation

Since an implicit implementation must respect names of members defined by the interface type, there's a high probability for name conflicts. The solution is explicit implementation:

// Dispose is not declared with the class.
MyClass = class(IDisposable)
end;

implementation for MyClass is

    // Instead, it's declared in the implementation section,
    // and is prefixed with the interface name.
    method IDisposable.Dispose;
    begin
        // Whatever...
    end;

Freya provides a third useful technique for implementing interface types: interface delegation. Interface delegation allows the programmer to reuse an existing interface implementation.

See also

The Freya Programming Language
Type declarations
Interface types
Class declarations
Inheritance clause
Interface delegations