Method overriding and method hiding in C#
In C#, method overriding and method hiding are two different mechanisms for modifying inherited methods.
Method Overriding
Method overriding involves creating a virtual method in the base class and redefining its implementation in the derived class. This allows derived classes to provide more specific or modified versions of methods while retaining the same method names and parameters.
Method overriding is used in the following situations:
override
keyword in method declarations in derived classes. Method Hiding
Method hiding involves creating a new method (new) with the same name and parameters as the base class method. Unlike method overriding, method hiding creates a completely new method in the derived class and does not modify the base class method.
Method hiding is used in the following situations:
new
keyword in method declarations in derived classes. Practical Application
Method Overriding:
Method Hiding:
Example
The following example demonstrates method overriding and method hiding:
<code class="language-csharp">class Animal { public virtual void MakeSound() { Console.WriteLine("Generic animal sound"); } } class Dog : Animal { public override void MakeSound() { Console.WriteLine("Bark"); } public new void Run() // 方法隐藏 { Console.WriteLine("Dog running"); } }</code>
In this example, the MakeSound
method is overridden in the Dog
class to provide a concrete implementation. The Run
method is hidden and a new method is created in the Dog
class.
The above is the detailed content of Overriding vs. Hiding in C#: What's the Difference?. For more information, please follow other related articles on the PHP Chinese website!