Dilshod K
Dilshod K

Reputation: 3032

Inherit two classes and implement from interface separately

I have abstract BaseClass and IClass interface. I created two classes Class(in different namespaces) and inherit from BaseClass. Does it make sense when I implement interface in Class classes, but not in BaseClass class?

Upvotes: 1

Views: 42

Answers (1)

Caius Jard
Caius Jard

Reputation: 74605

I don't see why not; the subclasses may have different implementations of IClass, they just conform to the IClass spec. You may have another implementation of Class that doesn't implement IClass, so it doesn't make sense to make BaseClass implement it (or abstract it) and force it upon all its children.

These are design decisions rather than hard and fast rules and depend a lot on the object space you're modelling. If something is common to all Class, consider making it part of the base class. If something is a specialism only a few Class will exhibit, make it an interface so they may be treated commonly for that specialism

In terms of examples, suppose you were creating a suite of collections (data storage devices, like Queue, List etc - I pick on these because they're commonly used, understood and people are used to them implementing interfaces).

You've decided that all collections shall support add and remove but only some of them can be enumerated. Add/Remove would be abstract methods of a base class, enumeration related operations would be specified in an interface. Not all the concrete subclasses of the base implement the interface and hence not all of them can be used in other places that declare "I'll take anything that implements enumeration"

Upvotes: 1

Related Questions