Site icon Embarcadero RAD Studio, Delphi, & C++Builder Blogs

Class Implementing Two Interfaces with Duplicate Method Names

the future of starts demands massive productivity

Delphi only supports single inheritance. A Delphi class can only descend from a single parent class, but a Delphi class can implement multiple interfaces.

[crayon-67629db9df8ac257995342/]

The TAthlete descends from the THuman parent class (which presumably descends from TInterfacedObject) and it implements both the IWalker and IJumper interfaces. What if both IWalker and IJumper contain a run method.

[crayon-67629db9df8b3561383226/]

Right now TAthlete doesn’t implement the members of IWalker or IJumper.

When we implement these interfaces in TAthlete, what if we want to have a different run method for IWalker vs IJumper? Enter the Method Resolution Clause.

Interface Method Resolution Clause

When a class implements two or more interfaces that have identically named methods, use method resolution clauses to resolve the naming conflicts. You can override the default name-based mappings by including method resolution clauses in a class declaration. We might implement those interfaces like this:

[crayon-67629db9df8b6475269225/]

But what happens if I call Run on a class reference to an TAthlete object? It doesn’t exist. There is no Run method on TAthlete, and both PowerWalk and RealRun are private, so they aren’t accessible via a class reference either.

[crayon-67629db9df8bd410949857/]

If we wanted to call Run on TAthlete we could do that with a little change.

[crayon-67629db9df8c0970927365/]

Now IJumper uses the default name-based mapping, which IWalker uses the manually mapped method

[crayon-67629db9df8c1428462546/]

It seems like it would usually be a good idea to be explicit in all the methods implemented by interfaces when you have a conflict like this, but there could be a reason to be less explicit in certain use cases. It is great that Delphi gives you the flexibility to implement this either way necessary.

Exit mobile version