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






你可能感興趣的文章

Dijkstra's Algorithm

Dijkstra's Algorithm

DAY7:Count by X

DAY7:Count by X

【前端學習】innerText 與 textContent 的差異

【前端學習】innerText 與 textContent 的差異






留言討論