2

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;
1

2 Answers 2

5

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.

Sign up to request clarification or add additional context in comments.

Comments

4

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.

3 Comments

Thanks for share. I prefer do sub-class as it's much more simple.
Actually this is a form of sub-classing. The class is modified at runtime. This is the view point that the contents of the VMT are part of the class definition, so therefore changing the VMT is changing the class.
@DavidHeffernan Not only a form of sub-classing, it is sub-classing because the class that is created by the TVirtualMethodInterceptor actually inherits from the class you passed in (just print out the class hierarchy).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.