C#學(xué)習(xí)筆記<三> 繼承

m_<:這里記錄C#學(xué)習(xí)的筆記,基礎(chǔ)的語(yǔ)法略去,重點(diǎn)在類、方法、繼承三項(xiàng)。

1 類繼承

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            Chinese p1 = new Chinese();
            Japanese p2 = new Japanese();
            p1.Name = "ZhengLantern";
            p1.Age = 20;
            p1.Hometown = "WuHan";
            p1.Kongfu();
            p1.SayHello();
            p2.QRZ();
            Console.ReadKey();
        }
    }

    class Person
    {
        public string Name {get; set;}
        public int Age {get; set;}
        public void SayHello()
        {
            Console.WriteLine("{0}", this.Name);
        }
    }
    class Chinese : Person   //繼承Person
    {
        public string Hometown { get; set; }
        public void Kongfu()
        {
            Console.WriteLine("KO!");
        }
    }
    class Japanese : Person   //繼承Person
    {
        public void QRZ()
        {
            Console.WriteLine("Stay at home.");
        }
    }
}

2

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            Chinese p1 = new Chinese();
            Person p2 = p1;   //定義一個(gè)Person,并指向Chinese
            //Chinese p3 = p2;   類型錯(cuò)誤
            Chinese p3 = (Chinese)p2;   //強(qiáng)制類型轉(zhuǎn)換
            p1.Name = "ZhengLantern";
            p1.Age = 20;
            p1.Kongfu();
            p2.SayHello();
            Console.ReadKey();
            object ob = p1;   //object是所有類的基類
        }
    }

    class Person
    {
        public string Name {get; set;}
        public int Age {get; set;}
        public void SayHello()
        {
            Console.WriteLine("{0}", this.Name);
        }
    }
    class Chinese : Person
    {
        public string Hometown { get; set; }
        public void Kongfu()
        {
            Console.WriteLine("KO!");
        }
    }
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容