構造函數及其重載and繼承

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication2
{
    class Program
    {
        static void Main(string[] args)
        {
            //person p1 = new person();
            //person p2 = new person("小紅");
            //person p3 = new person("小芳", 18);

            //Console.WriteLine("名字是{0},年齡爲{1}",p1.Name,p1.Age);
            //Console.WriteLine("名字是{0},年齡爲{1}",p2.Name,p2.Age);
            //Console.WriteLine("名字是{0},年齡爲{1}",p3.Name,p3.Age);
            //構造函數的重載 能夠更好的封裝類 不用訪問其內部成員 開始訪問時就直接給它參數  不用知道函數將如何對參數進行處理
    
            中國人 c1 = new 中國人();     //構造函數是不能被其他子類所繼承的
            c1.Name = "李小龍";
            c1.Sayhello();
            c1.戶口 = "西安";
            c1.中國功夫();
            韓國人 h1 = new 韓國人();     //子類可以繼承其父類的一般屬性
            h1.Name = "金三順";
            h1.棒子();
            h1.做泡菜();

            person p1 = c1;
            p1.Sayhello();

            中國人 c2 =(中國人) p1;  //可加類型轉換 使其人類轉換爲中國人類  
            c2.Sayhello();


            Console.ReadKey();
            
           

        }
    }
    class person:Object  //所以類全部繼承於Object類
    {   
        public string Name{set;get;}
        public int Age{set;get;}

        public void Sayhello()
        {
            Console.WriteLine("我的名字叫{0}",this.Name);
        }
        public person()
        {
            Name="未命名";
            Age=0;
        }
        public person(string name)
        {
            Name=name;
        }
        public person(string name,int age)
        {
            Name=name;
            Age=age;
        }
    }
    class 中國人:person
    {
        public string 戶口
        { get; set; }
        public void 中國功夫()
        {
            Console.WriteLine("我打!!!");
        }

    }
    
    
    class 韓國人:person
    {
        public void 做泡菜()
        {
            Console.WriteLine("泡 泡菜");
        }
        public void 棒子()
        {
            Console.WriteLine("西遊記是我們寫的");
        }
    }
}

發佈了31 篇原創文章 · 獲贊 9 · 訪問量 14萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章