When using interfaces, are the implementing class methods forced to return interfaces, or is there a way to return objects?
An example will clarify:
in unit EmployeeIntf:
IEmployee = interface(IInterface)
function CoWorker: IEmployee; // We dont know anything about TEmployee here
end;
in unit Employee:
uses EmployeeIntf;
...
TEmployee = class(TObject, IEmployee)
public
function CoWorker: IEmployee; // Returns an error if set to TEmployee
end;
Current code stops on a compiler error if the method returns a TEmployee: E2211 Declaration of 'CoWorker' differs of declaration in interface IEmployee (using Delphi 2010)
Is the TEmployee.CoWorker method forced to return an interface, or is there a way to return a TEmployee instead, as far as the TEmployee is a IEmployee?
If only interfaces are allowed in this case, what are the OO design reasons for that?
[Edit]
As asked by many contributors, I dont need ref counting on TEmployee and would like to isolate the above question from any ref counting consideration.
The background of this question is a need to use a very limited set of public functions of TEmployee in an external component (in a separate package). I can't simply import the 'Employee' unit in the package because of too many uneeded dependencies in uses sections, so I'm looking for a loosely coupling solution.
Thanks,
You can make the compiler happy by introducing a method resolution clause:
type
TEmployee = class(TInterfacedObject, IEmployee)
function IEmployee.CoWorker = IEmployeeCoWorker;
public
function IEmployeeCoWorker: IEmployee;
function CoWorker: TEmployee;
end;
function TEmployee.IEmployeeCoWorker: IEmployee;
begin
result := CoWorker;
end;
Of course, this will complicate the code, but if it actually is what you need...
are the implementing class methods forced to return interfaces?
No, but implementations are forced to match the signatures of the interface definitions.
is there a way to return objects?
Yes, if you declare the interface accordingly.
type
IEmployee = interface
function CoWorker: TEmployee;
end;
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