You can't require someone to call a method, except for the constructor. But a class's behavior shouldn't be in the constructor or called from the constructor. A class shouldn't start doing something just because we instantiated it. It should do something when we call its methods.
When we design a class it typically has one or two methods which are the primary responsibility of that class. Whoever creates an instance of the class is going to call one or more of those methods because that's the only reason why the class exists.
Instead of adding another method and expecting others to call it, you design the class so that the primary methods cannot be overridden. The only public
methods are in the base class. The methods that get overridden aren't public. That way the base class methods always get called, and if there's something you want the base class to always do, it always gets done.
That way other classes don't change the required base class behavior. They only extend it.
public abstract class TheBaseClass
{
public void DoSomething()
{
AlwaysDoThis();
InheritedClassBehavior();
}
private void AlwaysDoThis()
{
//This method in the base class always gets called.
//You don't need to explicitly require someone
//to call it.
}
protected abstract void InheritedClassBehavior();
}
public class TheInheritedClass : TheBaseClass
{
protected override void InheritedClassBehavior()
{
//The inherited class has its own behavior here.
//But this method can't be called directly because
//it's protected. Someone still has to call
//DoSomething() in the base class, so AlwaysDoThis()
//is always called.
}
}
InheritedClassBehavior
is protected, so nothing can call it directly. The only way to call it is by calling DoSomething
, which will always call the method in the base class, AlwaysDoThis()
.
InheritedClassBehavior
is abstract
, so inherited classes must implement it. Or you could make it virtual
- it has an implementation in the base class but an inherited class can override it. (If there aren't any abstract
methods then the base class doesn't need to be abstract
. The base class would only be abstract
if you want to prevent creating instances of the base class, only allowing creation of inherited classes.)