Calling Base's Method Directly
In OOP, accessing base class methods within derived classes is essential for method overriding. However, the question arises: "How can we call the base's base method, bypassing any intermediate overrides?"
To avoid the undesired call to Derived.Say() in the SpecialDerived class, the original source code cannot be modified. However, a workaround exists. By introducing a new method, CustomSay(), in the Derived class and overriding it in SpecialDerived, we can redirect the default behavior while preserving the existing Say() method.
Here's the modified code:
// Cannot change source code class Derived : Base { public override void Say() { CustomSay(); base.Say(); } protected virtual void CustomSay() { Console.WriteLine("Called from Derived."); } } class SpecialDerived : Derived { protected override void CustomSay() { Console.WriteLine("Called from Special Derived."); } }
Now, when calling sd.Say(), the result will be:
Called from Special Derived. Called from Base.
The use of a new method CustomSay() allows for customization without modifying the overridden Say() method. However, it's generally discouraged to access base methods beyond the first level due to its potential for confusion and maintenance issues.
The above is the detailed content of How to Call a Base Class Method Directly, Bypassing Intermediate Overrides?. For more information, please follow other related articles on the PHP Chinese website!