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






你可能感興趣的文章

用 Python 自學資料科學與機器學習入門實戰:Numpy 基礎入門

用 Python 自學資料科學與機器學習入門實戰:Numpy 基礎入門

Leetcode 刷題 pattern - Fast & Slow Pointer

Leetcode 刷題 pattern - Fast & Slow Pointer

從前端傳資料給後端(GET, POST)、從 PHP 連線到 MySQL 資料庫

從前端傳資料給後端(GET, POST)、從 PHP 連線到 MySQL 資料庫






留言討論