What is interface-interface inheritance in Pascal?
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.
Code example
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.
Code explanation
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
Interfacekeyword, and define a parent interface calledmyParentInterfaceincluding one member function namedmyPFunc.Lines 9–11: We use the
Interfacekeyword, and define a child interface calledmyChildInterfaceextending the base interfacemyParentInterfaceand including one member function namedmyCFunc.Lines 13–26: We define a class
myClassimplementing the child interface previously declared. To avoid errors in compilation, we should also inherit from a base objectTInterfacedObject. This class must include the definition of themyPFuncfunction already declared in the parent interface as well as the definition of the functionmyCFuncdeclared earlier in the child interface.Lines 28–29: We declare a variable
cl1having as type the class already defined.Line 33: We create an instance of the
myClassclass and store it in the variablecl1previously declared.Lines 34–35: We invoke the functions included within the class and display their respective results.
Free Resources