9.5.1 How it works
Interface declares method signatures without bodies. A class realizes it explicitly with Realizes, and must then declare those methods with the exact signature.
Cuadrado and Circulo realize Figura. Describir only knows the promise and accepts both.The interface Figura with the method Area. The classes Cuadrado and Circulo realize it. Below, Describir with the parameter T: Figura, which accepts both.
Interfaces are not value types: no variables of an interface type are declared. They are used as a constraint on a generic type parameter: T: Figura accepts any class that realizes Figura.
ProgramAn interface as a constraint
Interface Figura
Method Area() As Real;
EndInterface
Class Cuadrado Implements Figura
Define lado As Real;
Method Constructor(l As Real)
This.lado <- l;
EndMethod
Method Area() As Real
Return This.lado * This.lado;
EndMethod
EndClass
Class Circulo Implements Figura
Define radio As Real;
Method Constructor(r As Real)
This.radio <- r;
EndMethod
Method Area() As Real
Return 3.0 * This.radio * This.radio;
EndMethod
EndClass
Subroutine Describir<T: Figura>(figura As T)
Write "Área: ", figura.Area();
EndSubroutine
Algorithm Figuras
Describir(New Cuadrado(2.0));
Describir(New Circulo(1.0));
EndAlgorithmOutput
Área: 4.0 Área: 3.0
The program finishes normally.
Realization is nominal: a class that happens to have an Area method but does not declare Realizes Figura does not satisfy the interface. A class can realize several interfaces, separated by commas, and a subclass inherits the realizations of its superclass.
In short
- An interface declares signatures without bodies.
- A class satisfies it by saying so with
Realizesand with exact signatures. - It is used as a generic constraint, not as a variable type.