In Pascal programming language, an interface acts like an abstract class, including a group of related methods but with empty bodies.
In Pascal, it is possible for interfaces to inherit from one another, just like classes do. As a result, an interface can be descended from another interface.
Hence, when a class implements an interface, it has to implement all the child interface's functions as well as all the base/parent interface's functions.
Generally, interfaces are used to achieve security and conceal certain details, and they specify what a class must do, not how it should do it.
The following figure exhibits the inheritance hierarchy:
Let's look at the following example:
How a child interface inherits from another one.
How a class implements a child interface must provide all the methods required by the inheritance chain.
Let's look at the code below:
program hello;{$mode objfpc}typemyParentInterface = InterfaceFunction myPFunc : Integer;end;myChildInterface = Interface (myParentInterface)Function myCFunc : Integer;end;myClass = Class(TInterfacedObject,myChildInterface)Function myPFunc : Integer;Function myCFunc : Integer;end;Function myClass.myPFunc : Integer;beginResult := 5;end;Function myClass.myCFunc : Integer;beginResult := 10;end;varcl1 : myClass;beginwriteln('Start...');cl1:=myClass.create;writeln('cl1.myPFunc = ',cl1.myPFunc());writeln('cl1.myCFunc = ',cl1.myCFunc());writeln('End...');end.
Let's go through the code widget above:
Line 1: We refer to the program header. It is used for backward compatibility, and the compiler ignores it.
Line 2: This is a directive to the compiler to allow defining classes.
Lines 4–7: We use the Interface
keyword, and define a parent interface called myParentInterface
including one member function named myPFunc.
Lines 9–11: We use the Interface
keyword, and define a child interface called myChildInterface
extending the base interface myParentInterface
and including one member function named myCFunc.
Lines 13–26: We define a class myClass
implementing the child interface previously declared. To avoid errors in compilation, we should also inherit from a base object TInterfacedObject
. This class must include the definition of the myPFunc
function already declared in the parent interface as well as the definition of the function myCFunc
declared earlier in the child interface.
Lines 28–29: We declare a variable cl1
having as type the class already defined.
Line 33: We create an instance of the myClass
class and store it in the variable cl1
previously declared.
Lines 34–35: We invoke the functions included within the class and display their respective results.
Free Resources