Coding in Delphi book has this example about interface constraint :
1 type
2 IStoppable = interface
3 procedure Stop;
4 end;
5
6 TWidget<T: IStoppable> = class
7 FProcess: T;
8 procedure StopProcess;
9 end;
10
11 { TWidget<T> }
12
13 procedure TWidget<T>.StopProcess;
14 begin
15 FProcess.Stop;
16 end;
I don't understand in line 15 how he call the "Stop" method?? isn't FProcess is a generic variable? So how can he call a method from a variable?
Also how can he call the "Stop" method directly from an interface? Isn't it supposed to call the implemented method?
FProcess
is of type T
where T
is constrained to be an interface that is IStoppable
or one derived from IStoppable
. The method call you refer to therefore calls the Stop
method of IStoppable
.
Imagine instead that FProcess
was declared to be of type IStoppable
.
FProcess: IStoppable;
If that were so then I think you would understand the code.
Whenever you find yourself struggling to understand generic code this is a useful technique. Replace the generic type with a concrete type and read the code again. It is often much easier to understand concrete code and that understanding will then help you generalise to the generic code.
As far as where the method is implemented that is no different here as for a concrete interface. An interface defines the interface but leaves the implementation unspecified. The class that implements the interfaces specifies that but you don't need to know about that in order to use an interface. That's really the modus operandi for interfaces.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With