多态与接口

今天在云和学院学了多态和接口,今天总结的可能不是很准确。

多态——抽象类与抽象方法由abstract修饰
abstract的使用注意
–抽象方法没有方法体
–抽象成员只能存在于抽象类中
–抽象类可以有非抽象成员
–抽象类的派生类必须实现抽象方法体
–抽象类只能用作基类,无法实例化
用virtual修饰的方法叫做虚方法
虚方法可以在子类中通过override关键字来重写
虚方法抽象方法比较
namespace Abstract
{
    class chinese:person
    {
        public override void sayhi()
        {
            Console.WriteLine();
        }
    }
}

abstract class person
    {
        public string name { set; get; }
        public void sayhello()
        {

        }
        abstract public void sayhi();
    }

virtual实例:

enum Gender
    {
        雌 = 1,
        雄 = 2
    }
    class Bird
    {


        public virtual string Berk()
        {
            return "鸟鸣";
        }
        public string BName { set; get; }
        public Gender BGender { set; get; }

        public string Color { set; get; }

        public string Category { set; get; }

        public string Fly()
        {
            return "我会飞";
        }
        public string Eat()
        {
            return "吃饭";
        }

        public string Sleep()
        {
            return "睡觉";
        }

        public string Walk()
        {
            return "走路";
        }
    }



 class Polly:Bird
    {
        public string WeiBa { set; get; }

        public string SayHi(string word)
        {

            return word;
        }
        public override string Berk()
        {
            return "我会学人说话";
        }
   }


class dayan:Bird
    {
        public override string Berk()
        {
            return "大雁南飞";
        }
    }

static void Main(string[] args)
        {
            Bird b = new Polly();
            Console.WriteLine(b.Berk());
            dayan yan = new dayan();
            Console.WriteLine(yan.Berk());
            Console.ReadKey();
        }

 接口:完全抽象的一种约定,接口就是用来实现的。

 语法:

[访问修饰符] interface 接口名

{

    // 接口成员定义

}

Interface IfFly

{

  void IFly();

}

interface Ifly
    {
        void Fly();
    }


class Maque:Bird,Ifly
    {
        void Ifly.Fly()
        {
            Console.WriteLine("麻雀飞了");
        }
    }



class Program
    {
        static void Main(string[] args)
        {
            Ifly fly = new Maque();
            fly.Fly(); 
            Console.ReadKey();
            
        }
    }
 
原文地址:https://www.cnblogs.com/songfang/p/4111398.html