No language I know of enforces calling the overridden method. Indeed, some languages allow overriding methods that are not overridable (such as using the new
keyword in C#). However, there are two ways of approaching this.
The first is to create an unoverridable method (e.g. one that lacks the virtual
keyword in C# or one that has the final
keyword in Java) that calls an overridable one that cannot be called from outside the class (e.g. protected
in C#, Java or C++).
class C
A
statement1
F
statement3
protected virtual F
statement2
and
class D inherits C
protected override F
statement4
C.F()
Classes overriding C
are free to override the F
and modify its behavior but callers from outside the class only access it through A
.
Edit: As others have pointed out, this is called the Template method pattern.
The second way is to use a language that enforces preconditions and postconditions specified in the base class, like Eiffel or C# with Code Contracts. It will not force the base class to be called but the overridden method can be forced to perform the same statements. Using aspects may also help if the language allows aspects to be inherited.