Reputation: 464
Just curious, can i construct an abstract class in Delphi like Java Style?
Java Declaration:
public abstract class Foo {
public abstract void test();
}
Way to use :
public void testCsontruct() {
Foo clsfoo = new Foo(){
public void test(){
//....do something here
}
};
}
Delphi declaration :
Tfoo = class
public
procedure test; virtual; abstract;
end;
Way to use :
procedure testUse;
var
foo:Tfoo;
begin
foo:=Tfoo.Create; //can we implement the test method here ? how?
end;
Upvotes: 2
Views: 415
Reputation: 612964
That Java functionality is the anonymous class. They are useful in a number of scenarios. As well as that which you illustrate, they are commonly used to capture variables in the enclosing scope.
There is nothing quite like that syntax in Delphi. Anonymous methods come close, but there's no syntax to allow you to replace a virtual method of an instantiated object with an anonymous methods.
You need to sub-class to provide a concrete implementation of the virtual method. You can sub-class at compile time in the usual way, or at run time using virtual method interceptors or some similar VMT trickery.
Upvotes: 5
Reputation: 380
You can do that with virtual method interceptors:
uses
Rtti;
...
begin
foo := TFoo.Create;
vmi := TVirtualMethodInterceptor.Create(foo.ClassType);
vmi.OnBefore :=
procedure(Instance: TObject; Method: TRttiMethod; const Args: TArray<TValue>; out DoInvoke: Boolean;
out Result: TValue)
begin
if Method.Name = 'test' then
begin
DoInvoke := false;
// do something here
end;
end;
vmi.Proxify(foo);
foo.test;
foo.Free;
vmi.Free;
end;
However, I would prefer an actual implementation in a subclass.
Upvotes: 4