Reputation: 13582
Is it possible to force the derived classes of a class to implement an interface?
Let's say I have Interface IImportantStuff
and Classes Base
and DerivedA
, DerivedB
,DerivedC
and ...
I want to force DerivedA, DerivedB, DerivedC and all other classes that will inherit Base class in future (classes I may design in future) to implement IImportantStuff.
Editted:
As another question, Each inherited class (derived from Base class) works with a certain Entity (say Customer, Shopkeeper, Personnel) and I want to force the derived classes to declare their Entity to prevent the programmers on my team creating a class inherited from Base without defining the Entity. I wanted to do this via Generics and Interfaces so that on the Base form they can access the properties and members of the Entity.
For example
class Base<T> { public T Entity {get; set;} }
class MidClass : Base {}
class Customer
{
public string CustomerName {get; set;}
}
class Shopkeeper
{
public int ShopkeeperID {get; set;}
}
class Shop1 : Base<ShopKeeper>
{
//1. Force the programmer to implement ShopkeeperID
//2. Be able to access the properties of Shopkeeper
void MyMethod()
{
var skid = this.Entity.ID;
}
}
class Shop2 : Base<Customer>
{
void MyMethod()
{
var skid = this.Entity.CustomerName;
}
}
I want Shop1 and Shop2 to inherit Base class, not directly the interface, because my co-programmers may forget to inherit from Interface on their classes. So I want to do the force on MidClass and their classes which are inherited from MidClass should implement the interface.
Upvotes: 0
Views: 350
Reputation: 125610
As long as your Base
class implements IImportantStuff
all derived classes will implement it as well.
If you want derived methods to provide implementations you'd need to make Base
class abstract and mark all methods/properties from that interface abstract
.
Upvotes: 3
Reputation: 35646
one way is to declare Base class as abstract and make methods and properties IImportantStuff absract:
public interface IImportantStuff
{
void Action();
}
public abstract class Base: IImportantStuff
{
public abstract void Action();
}
Upvotes: 3