最简单的抽象类与多态
抽象类包含抽象成员(该成员不提供任何实现,但强迫子类对其实现),不可实例化。
多态:举个例子:同一个方法,在不同的子类中重写,然后统一调用,则呈现出不同的效果。
基类:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
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 PdaItem 10 { 11 public PdaItem(string name) 12 { 13 Name = name; 14 } 15 public virtual string Name { get; set; } 16 public abstract string GetSummary();//纯虚函数,强制子类实现,他也实现了多态 17 } 18 }
下面为两个子类:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
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 Name 16 { 17 get 18 { 19 return FirstName + " " + LastName; 20 } 21 set 22 { 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 }
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
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.NewLine 20 + "Start:{1}" + Environment.NewLine 21 + "End:{2}" + Environment.NewLine 22 + "Location:{3}", 23 Name, StartDateTime, EndDateTime, Location 24 ); 25 } 26 } 27 }
主函数中的实现:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
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 }
运行结果: