How to implement method overriding and hiding in C#?

In C#, method overriding and hiding are achieved through inheritance and access modifiers.

  1. Override method: When a subclass rewrites a method of the parent class, the “override” keyword can be used. The overridden method must have the same name, parameter list, and return type as the parent class method. For example:
class BaseClass
{
    public virtual void Print()
    {
        Console.WriteLine("Base Class");
    }
}

class DerivedClass : BaseClass
{
    public override void Print()
    {
        Console.WriteLine("Derived Class");
    }
}

BaseClass baseObj = new DerivedClass(); // 创建子类对象,调用子类的Print方法
baseObj.Print(); // 输出:"Derived Class"
  1. Method hiding: In a subclass, hiding a method from the parent class can be done using the ‘new’ keyword. The hidden method does not need to have the same name, parameter list, or return type as the parent class method, but it is recommended for clarity to keep them consistent to avoid confusion. An example is shown below:
class BaseClass
{
    public void Print()
    {
        Console.WriteLine("Base Class");
    }
}

class DerivedClass : BaseClass
{
    public new void Print()
    {
        Console.WriteLine("Derived Class");
    }
}

BaseClass baseObj = new DerivedClass(); // 创建子类对象,调用父类的Print方法
baseObj.Print(); // 输出:"Base Class"

Through these two methods, it is possible to achieve method overriding and hiding, allowing subclasses to customize the processing of parent class methods.

Leave a Reply 0

Your email address will not be published. Required fields are marked *


广告
Closing in 10 seconds
bannerAds