Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to support class methods in interface definitions in Delphi

I created a class method in a class that implements an interface, but I can't seem to define it inside of the interface.

IMyClass = interface
  procedure someproc();
  class function myfunc() : TMyClass;  // compiler doesn't like this!
end;

TMyClass = class( TInterfacedObject, IMyClass )
public
  procedure someproc();
  class function myfunc() : TMyClass;
end;

I want myfunc() to create and return an instance of TMyClass. For example:

somefunc( TMyClass.myfunc(), ... );

creates an instance of TMyClass and passes it into somefunc.

I can define function myfunc() : TMyClass; in the IMyClass interface, but if I put class in front of it, the compiler gives me an error. If I leave it off, it gives me several other errors "E2291 Missing implementation of interface method xyz.myfunc" It just doesn't accept the same signature in the interface as in the class.

I thought I've seen this work before (class methods defined in interfaces) but maybe not.

If this isn't supported directly, how do you do it?

(I'm using Delphi XE5, in case it matters.)

like image 594
David Schwartz Avatar asked Oct 03 '14 18:10

David Schwartz


People also ask

How do you implement an interface in Delphi?

To generate a new GUID value, just press Ctrl+Shift+G in the Delphi IDE. Each interface you define needs a unique Guid value. An interface in OOP defines an abstraction—a template for an actual class that will implement the interface—that will implement the methods defined by the interface.

What is the difference between a class and an interface?

A class describes the attributes and behaviors of an object. An interface contains behaviors that a class implements. A class may contain abstract methods, concrete methods. An interface contains only abstract methods.

What is a class function Delphi?

In Delphi, a method is a procedure or function that performs an operation on an object. A class method is a method that operates on a class reference instead of an object reference.

What does it mean to implement an interface?

Implementing an interface means to actually write some code to fulfill the description of the interface, in terms of function names, attributes and return values.


1 Answers

Interfaces are not classes and do not support methods marked as class, they only support non-class methods that are implemented and called on object instances.

What you are looking for will most likely have to be implemented as a class factory instead of using an interface.

like image 78
Remy Lebeau Avatar answered Sep 29 '22 13:09

Remy Lebeau