JustMe
JustMe

Reputation: 2383

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?

Upvotes: 2

Views: 2247

Answers (2)

David Heffernan
David Heffernan

Reputation: 613272

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.

Upvotes: 7

GolezTrol
GolezTrol

Reputation: 116140

Of course you can choose to implement the interface in a common ancestor, or at least have a common ancestor for the classes that implement the interface. However, you cannot enforce this through the interface. An interface has no constructor and an interface cannot enforce which class can or cannot implement it.

I think the best option would be to expose an Owner property through the interface. That way, you can at least get the owner through the interface, and you will enforce the implementing classes to at least implement that property. B.t.w, an interface is allowed to have properties and methods that return objects or have object parameters.

Upvotes: 4

Related Questions