I have a concrete top-class FooBase and an interface IFoo:
public class FooBase
{
//some code
}
public interface IFoo
{
void DoBar();
}
every child-classes FooChild implements and extends both:
public class FooChild : FooBase, IFoo
{
public void DoBar()
{
//some implementation
}
}
Can concrete FooBase define the signature of an empty method in order to delegate the implementation to child-classes as IFoo interface does?
CodePudding user response:
There are three ways in which a base class can allow or force it's inheritors to implement the desired signature:
1. Virtual method (allows to implement)
public interface IFoo { void DoBar(); }
public class Foo : IFoo { public virtual void DoBar() { /*Default impl. */ }
public class FooChild : Foo { public override void DoBar() { /* Child impl. */ }
2. Abstract method (forces to implement)
public interface IFoo { void DoBar(); }
public abstract class FooBase : IFoo { public abstract void DoBar(); }
public class FooChild : FooBase { public override void DoBar() { /* Child impl. */ }
3. Abstract separated method (forces to implement, no direct logical attachment to the interface)
public interface IFoo
{
void DoBar();
}
public abstract class FooBase : IFoo
{
public void DoBar() { DoBarRelatedWork(); }
protected abstract void DoBarRelatedWork();
}
public class FooChild : FooBase
{
public override void DoBarRelatedWork() { /* Child impl. */ }
}