·您现在的位置: 云翼网络 >> 文章中心 >> 网站建设 >> 网站建设开发 >> ASP.NET网站开发 >> 黑马程序员-接口

黑马程序员-接口

作者:佚名      ASP.NET网站开发编辑:admin      更新时间:2022-07-23

黑马程序员-接口

接口

接口是完全抽象的一种约定。

接口就是用来实现的。

语法:

[访问修饰符] interface 接口名

{

  //接口成员定义

}

接口只有方法、属性、索引和事件的声明

接口是用来实现的,所有成员默认为public

interface IWalkable

{

  //返回类型 方法名(参数列表);

  void Walk();

}

interface ISoundable

{

  void Sound();

}

abstractclassAnimal:IWalkable,ISoundable

{

publicabstractvoidWalk();

publicabstractvoidSound();

}

classPerson:Animal

{

publicoverridevoidWalk()

{

Console.WriteLine("我是一个人,用两只脚在行走中……");

}

publicoverridevoidSound()

{

Console.WriteLine("我是一个人,在说话,用到是语言哦");

}

}

classTeacher:Person

{

//老师,没有重写父类方法

}

classStudent:Person

{

publicoverridevoidSound()

{

Console.WriteLine("我是学生重写的Sound方法");

}

//publicoverridevoidWalk()

//sealed是密闭的意思,表示从这里开始不允许再被Student的子类重写了

publicsealedoverridevoidWalk()

{

Console.WriteLine("我是学生重写的Walk方法");

}

}

classChild:Student

{

publicoverridevoidSound()

{

Console.WriteLine("这是小孩的Sound");

}

publicnewvoidWalk()

{

Console.WriteLine("小孩的Walk");

}

}

classCat:Animal

{

publicoverridevoidWalk()

{

Console.WriteLine("猫猫走猫步,好迷人……");

}

publicoverridevoidSound()

{

Console.WriteLine("喵喵喵……");

}

}

classCar:IWalkable

{

publicvoidWalk()

{

Console.WriteLine("我是一辆卡车,走在大路上……");

}

}

classRadio:ISoundable

{

publicvoidSound()

{

Console.WriteLine("小喇叭,有开始广播啦!!!");

}

}

classPRogram

{

staticvoidMain(string[]args)

{

IWalkable[]walkObjects={newPerson()

,newCat()

,newCar()

,newTeacher()

,newStudent()

,newChild()};

for(inti=0;i<walkObjects.Length;i++)

{

walkObjects[i].Walk();

}

objectobj=newChild();

IWalkableiWalk=(IWalkable)obj;

Childchi=(Child)obj;

iWalk.Walk();//我是学生重写的Walk方法

chi.Walk();//小孩的Walk

//new为隐藏over重写隐藏看类型重写只管新爸

Console.WriteLine("\n----------------------\n");

ISoundable[]soundObjects={newPerson()

,newCat()

,newRadio()

,newTeacher()

,newStudent()};

for(inti=0;i<soundObjects.Length;i++)

{

soundObjects[i].Sound();

}

Console.ReadKey();

}

}