首页 > 代码库 > 最简单的抽象类与多态
最简单的抽象类与多态
抽象类包含抽象成员(该成员不提供任何实现,但强迫子类对其实现),不可实例化。
多态:举个例子:同一个方法,在不同的子类中重写,然后统一调用,则呈现出不同的效果。
基类:
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 6 namespace OverrideTest 7 { 8 //抽象类 9 public abstract class PdaItem10 {11 public PdaItem(string name)12 {13 Name = name;14 }15 public virtual string Name { get; set; }16 public abstract string GetSummary();//纯虚函数,强制子类实现,他也实现了多态17 }18 }
下面为两个子类:
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 6 namespace OverrideTest 7 { 8 class Contacts:PdaItem 9 {10 public Contacts(string name)//继承父类的构造函数11 : base(name)12 {13 Name = name;14 }15 public override string Name16 {17 get18 {19 return FirstName + " " + LastName; 20 }21 set22 {23 string[] names = value.Split(‘ ‘);24 FirstName = names[0];25 LastName = names[1];26 }27 }28 public string FirstName { get; set; }29 public string LastName { get; set; }30 public string Address { get; set; }31 public override string GetSummary()//强制重写32 {33 return string.Format("FirstName :{0}" + "LstName:{1}" + "Address:{2}", FirstName, LastName, Address);34 }35 }36 }
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 6 namespace OverrideTest 7 { 8 class Appointment:PdaItem 9 {10 public Appointment(string name):base(name)11 {12 Name = name;13 }14 public DateTime StartDateTime { get; set; }15 public DateTime EndDateTime { get; set; }16 public string Location { get; set; }17 public override string GetSummary()//强制重写18 {19 return string.Format("Subject:{0}" + Environment.NewLine20 + "Start:{1}" + Environment.NewLine21 + "End:{2}" + Environment.NewLine22 + "Location:{3}",23 Name, StartDateTime, EndDateTime, Location24 );25 }26 }27 }
主函数中的实现:
1 PdaItem[] pda = new PdaItem[3]; 2 3 Contacts contacts = new Contacts("Tom Li"); 4 contacts.Address = "Chongwen Road NananZone Chongqing City China"; 5 pda[0] = contacts; 6 7 Appointment appointment = new Appointment("Tms Cli"); 8 appointment.StartDateTime = new DateTime(2014, 10, 10); 9 appointment.EndDateTime = new DateTime(2014, 10, 11);10 appointment.Location = "Chongqing Unibersity of Posts and Telecommunictions";11 pda[1] = appointment;12 13 contacts = new Contacts("another one");14 contacts.Address = "thrity-thress dormitory";15 pda[2] = contacts;16 List(pda);17 }18 public static void List(PdaItem[] items)19 {20 foreach (PdaItem item in items)21 {22 Console.WriteLine("---------------------------");23 Console.WriteLine(item.GetSummary());//虽然调用的都是基类的同一个函数,但是基类的三个对象分别指向了不同的子类,所以他们都选择了各自的继承链里面重写的最远的那个。24 }25 }
运行结果:
最简单的抽象类与多态
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。