C# Inheritance, override modifier


What is inheritance

define:
We can have one class inherit all of the functionality of another class.

virtual, override

When we have virtual modifier with attribute or method on parent class, we can use override modifier to override it content on subclass.

Chef.cs

internal class Chef
{
    public void MakeChicken()
    {
        Console.WriteLine("The Chef makes chicken");
    }

    public void MakeSalad()
    {
        Console.WriteLine("The Chef makes salad");
    }

    public virtual void MakeSpecialDish()
    {
        Console.WriteLine("The Chef makes bbq ribs");
    } 
}

ItalianChef.cs

internal class ItalianChef : Chef
    {
        public override void MakeSpecialDish()
        {
            Console.WriteLine("Make special dish.");
        }

        public void MakePasta()
        {
            Console.WriteLine("The chef makes pasta.");
        }
    }

Program.cs

static void Main(string[] args)
{
    Inheritance();
}

private static void Inheritance()
    {
        Chef chef = new Chef();
        chef.MakeChicken();
        chef.MakeSpecialDish();

        ItalianChef italianChef = new ItalianChef();
        italianChef.MakeChicken();
        italianChef.MakePasta();
        italianChef.MakeSpecialDish();
        Console.ReadLine();
    }
#C#Note






你可能感興趣的文章

初試啼聲,只用原生 JS 跟 CSS 寫「口罩地圖 」Ep.02

初試啼聲,只用原生 JS 跟 CSS 寫「口罩地圖 」Ep.02

建立tsconfig檔做設定

建立tsconfig檔做設定

【Day05】Vuex

【Day05】Vuex






留言討論