Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Constructor in an Interface

I know - I cannot, but.

I want all classes who will implement my interface to have the same owner (usually defined in constructor). What is the best practice to do that?

Should I use some base abstract class or something like this?

like image 596
JustMe Avatar asked Dec 07 '25 09:12

JustMe


1 Answers

An interface defines a contract between implementor and consumer.

Part of that contract is enforced by the compiler. For example, that all implementations of the interface have the requisite functions of particular names, which take specific parameters.

But there is another part of an interface that is not enforced by the compiler. That's the part of the contract that is described in the interface documentation. You could decide that it suffices to tell all implementors what rules they must abide by. Many libraries take that stance. The Windows API is one prominent example.

If you are dead set on enforcement through code then an interface cannot help. You need something that expresses the constraint in code and in this case that's going to require implementation. Which means you would need to use a class. An (almost) abstract base class could get it done. The only concrete part of the class would enforce the ownership constraint. The rest of the class would be a series of abstract virtual methods. That's not an interface in the sense implied by the Delphi keyword. However, it's an interface in semantic terms.

like image 156
David Heffernan Avatar answered Dec 08 '25 23:12

David Heffernan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!