多态:让一个类能够表现多种状态(类型)。
实现多态的3种手段:虚方法,抽象类,接口
1、先介绍虚方法,父类方法用virtual标记(public virtual void SayHello() {......}),子类方法用override标记(public override void SayHello(){......}),父类中放入子类,当调用父类方法时会自动使用子类方法
举例说明
using System; namespace virsual_override { // class Program { static void Main(string[] args) { //English en1 = new English("Jim"); //English en2 = new English("Lucy"); //Korea kr1 = new Korea("金秀贤"); //Korea kr2 = new Korea("金正恩"); //Persion[] pers = { en1, en2, kr1, kr2 }; Persion[] pers = { new English("Jim"),new English("Lucy"),new Korea("金秀贤"),new Korea("金正恩")}; for (int i = 0; i < pers.Length; i++) { pers[i].SayHello(); } Console.Read(); } } class Persion { public string Name { get; set; } public Persion(string name) { this.Name = name; } public virtual void SayHello() { Console.WriteLine("我是人类"); } } class English : Persion { public string Name { get; set; } public English(string name) : base(name) { this.Name = name; } public override void SayHello() { Console.WriteLine("我是{0}", this.Name); } } class Korea : Persion { public string Name { get; set; } public Korea(string name) : base(name) { this.Name = name; } public override void SayHello() { Console.WriteLine("我是{0}", this.Name); } } }
结果显示:
2、抽象类
当父类中的方法不知道怎么实现的时候,可以考虑把父类写成抽象类,把方法写成抽象方法。
using System; namespace abstract_fangfa { class Program { static void Main(string[] args) { //Animal a = new Animal();这样会报错,抽象类不循序实体化 Animal a = new Dog(); a.Bark(); Console.Read(); } } public abstract class Animal { public abstract void Bark(); } public class Dog:Animal { public override void Bark() { Console.WriteLine("Dog wangwang Barking"); } } public class cat : Animal { public override void Bark() { Console.WriteLine("Dog miaomiao Barking"); } } }
结果
3、接口是一种规范,能力