Search code examples
delphidelphi-7

How to use Interface with VCL Classes?


In my previous question I was suggested to use Interface: How to implement identical methods with 2 and more Classes?

But nothing complies as I have no knowledge on how to use Interfaces.

I guess you can call this code pseudo :)

type
  IDoSomething = interface
    ['{EFE0308B-A85D-4DF3-889C-40FBC8FE84D0}']
    procedure DoSomething1;
    procedure WMSize(var Message: TWMSize); message WM_SIZE; // <- Unknown directive: 'message'
  end;

  TMyCheckBox = class(TCheckBox, IDoSomething) // <- Undeclared identifier: 'DoSomething1'
  end;

  TMyRadioButton = class(TRadioButton, IDoSomething) // <- Undeclared identifier: 'DoSomething1'
  end;

implementation

procedure IDoSomething.DoSomething1; // Identifier redeclared: 'IDoSomething'
begin
  // do the same thing for TMyCheckBox and TRadioButton
end;

procedure IDoSomething.WMSize(var Message: TWMSize);
begin
  // handle this message the same as with TMyCheckBox and TRadioButton
end;

How do I use the Interface to centralize the code? and How can I share new properties with the help of the Interface?


Solution

    1. the message keyword is not allowed in an interface method declaration. Remove message WM_SIZE; and the code will run fine until the compiler hits the second problem - see below

    2. Interface methods never have their own implementations. If the IDoSomething interface declares a method DoSomething1, the compiler will not allow to write an implementation like procedure IDoSomething.DoSomething1; like in your code - instead, the class which implements the interface has to provide the implementation body.