Unity3D開發(fā)-C#語言進階篇(面向?qū)ο笾鄳B(tài)-虛函數(shù)應(yīng)用詳解)

 class Program
    {
        static void Main(string[] args)
        {
            //1、有一個交通工具類Vehicle,
            //將它作為基類派生小車類Car、卡車類Truck和輪船類Boat,
            //定義這些類并定義一個虛函數(shù)用來顯示各類信息。
            //虛函數(shù)就是重寫           
            Vehicle car = new Car();
            //car.fun() 子類調(diào)用不了自己的普通方法 除非重寫;

            Vehicle truck = new Truck();
            Vehicle boat = new Boat();
            //car.ZuoYong();
            //truck.ZuoYong();
            //boat.ZuoYong();

            //2、定義貓科動物Animal類,由其派生出貓類(Cat)和豹類(Leopard),
            //二者都包含虛函數(shù) Sound( ),
            //要求根據(jù)派生類對象的不同調(diào)用各自重載后的成員函數(shù)(向上轉(zhuǎn)型)。


            Animal cat = new Cat();
            cat.Catch();
            cat.Catch("魚");

            Animal leoprad = new Leopard();
            leoprad.Catch();
            leoprad.Catch("喜羊羊");
        }
    }

 class Animal
    {
        public Animal()
        {
            // this.Catch();
        }


        //重載必須寫在同一個類中
        public void Catch()
        {

            Console.WriteLine("捕獲行為!");
        }

        public void Catch(string s)
        {

            Console.WriteLine("捕獲了:" + s);
        }

    }
 class Boat:Vehicle
    {
        public Boat()
        {
            this.ZuoYong();
        }

        public override void ZuoYong()
        {
            Console.WriteLine("子類--輪船的主要作用是在水上行走!");
        }
    }
 class Car:Vehicle
    {

        public Car()
        {

            this.ZuoYong();
        }

        public override void ZuoYong()
        {
            Console.WriteLine("子類-小汽車的主要功能是載人!");
        }

        public void fun()//自身的方法 如果由基類派生出子類;類對象名調(diào)用不了自己的方法;如:Vechicle car=new Car();
        {
            Console.WriteLine("子類自己的普通方法!");
        }
    
    }
 class Cat:Animal
    {
    }
 class Leopard:Animal
    {
    }
 class Truck:Vehicle
    {
        public Truck()
        {
            this.ZuoYong();
        }

        public override void ZuoYong()
        {
            Console.WriteLine("子類-卡車的主要作用是運輸貨物!");
        }
    }
  class Vehicle
    {
        private string name;

        public string Name
        {
            get { return name; }
            set { name = value; }
        }

        public virtual void ZuoYong() {
            Console.WriteLine("父類-交通工具主要是運輸!");
        
        }

        public Vehicle() {
            //this.ZuoYong();
        }
    }
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

推薦閱讀更多精彩內(nèi)容