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






你可能感興趣的文章

輕鬆理解 Ajax 與跨來源請求

輕鬆理解 Ajax 與跨來源請求

焦糖幫你記ChatBot || Line Bot 實作

焦糖幫你記ChatBot || Line Bot 實作

【THM Walkthrough】Breaching Active Directory

【THM Walkthrough】Breaching Active Directory






留言討論