Skip to content

Interfaces. An introduction

Interface-UML
Interface - UML

What does exactly mean "so short"?
Have you noticed what misses, comparing the previous code with the others we've used until now to write a class?

We'll be very concise.

First of all, the type definition: no more class or class(class to inherit) but only the interface keyword.
[And to be comfortable we begin the interface's name with a capital I, where T stands for Type instead, as we've already seen]

Second: an interface has no visibility modifiers.
Private, Protected and Public are not required because every item is inherently public.
And this is obvious, because every element must be redeclared; this implies they must be totally accessible form every class that inherits the interface.

Third: absolutely no attributes!
By nature the attributes have not to be redeclared, so we insert them directly into the class of interest.

Forth: no other modifier is required.
Neither abstract nor virtual are used: as said the interface makesĀ  all item really abstract (that is: forced to be redeclared).

Fifth: no implementation!
The code relative to the way a method works doesn't go here.
Remember that we're dealing with an empty holder, a kind of mask: don't care here about the goal of the methods.

[We wrote the interface in a separate file, but you can choose to write it inside another unit file]

Good.
Now, how to use it inside a class?

In our example the Employee class shows the right way:

type
  TEmployee = class(TInterfacedObject, IHuman) //inherits from the Interface

IHuman is inherited together with TInterfacedObject: there's no enough space to talk about this last class, but we can say that it's a way adopted by FreePascal (and Delphi) to make the interface communicate with objects.

And the implementation comes naturally as always:

...
//ALL Interface METHODS must be redefined !!!
    function GetSex():string;
    procedure SetSex(Sex_:string);
...
function TEmployee.GetSex():string;
begin
  result := self.Sex;
end;

procedure TEmployee.SetSex(Sex_:string);
begin
  self.Sex := Sex_;
end;

end.

Interfaces (introduced with Java programming language) are a powerful and elegant way to define abstract classes; to understand their utility think that in C++ (without specifying a particular implementation) they don't exist, so that a class becomes abstract only when every method is so declared.
The more methods you have in the class, the more job grows and bores.