接口的声明、实现和继承

题目描述  

老鹰、麻雀、鸵鸟都是鸟类,根据三者的共性,提取出鸟类作为父类;并且各自具有各自的特点,老鹰吃小鸡,麻雀吃粮食,鸵鸟吃青草。老鹰和麻雀都会飞,实现“飞”功能。(控制台应用程序)

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

namespace 接口的实现和继承
{
    class Program
    {
        static void Main(string[] args)
        {
            IFlyable[] flys = {new Eagle(),new Sparrow()};
            foreach(IFlyable outFly in flys)
                outFly.Fly();
        }
    }
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace 接口的实现和继承
{
   abstract class Bird
    {
        public abstract void Eat();
    }
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace 接口的实现和继承
{
    class Eagle:Bird,IFlyable
    {
        //接口的实现需要在实现接口的类中进行实现
        public void Fly()
        {
            Console.WriteLine("我是老鹰,我会飞");
        }
        public override void Eat()
        {
            Console.WriteLine("我是老鹰,我专吃小鸡");
        }
    }
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace 接口的实现和继承
{
    class Sparrow:Bird,IFlyable
    {
        public void Fly()
        {
            Console.WriteLine("我是麻雀,我会飞");
        }
        public override void Eat()
        {
            Console.WriteLine("我是麻雀,我专吃粮食");
        }
    }
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace 接口的实现和继承
{
    class Ostrich:Bird
    {
        public override void Eat()
        {
            Console.WriteLine("我是鸵鸟,我专吃青草");
        }
    }
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace 接口的实现和继承
{
    interface IFlyable
    {
        void Fly();
    }
}


***接口的声明

1.接口不能包含字段

2.接口成员不允许添加访问修饰符,默认就是public,成员也不能加abstract访问修饰符

3.接口不能包含实现其成员的任何代码,而只能定义成员本身(如不允许写具有方法体的函数)

4.实现过程必须在实现接口的类中完成

5.接口的成员可以是方法、属性、事件和索引器,但不能包含常数、字段、运算符、实例构造函数、析构函数或类型,也不能包含任何种类的静态成员

***接口的实现和继承

1.类继承具有单根性,接口可多重继承

2.父接口也称为该接口的显示基接口

3.接口多重继承时,派生接口名与父接口用冒号隔开,多个父接口之间用逗号隔开

扫描二维码关注公众号,回复: 565698 查看本文章



猜你喜欢

转载自blog.csdn.net/wyj____/article/details/80242090