面向对象的三个特征继承,封装和多态_第1页
面向对象的三个特征继承,封装和多态_第2页
面向对象的三个特征继承,封装和多态_第3页
面向对象的三个特征继承,封装和多态_第4页
面向对象的三个特征继承,封装和多态_第5页
已阅读5页,还剩7页未读 继续免费阅读

下载本文档

版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领

文档简介

1、下面重点说明面向对象的三个特征.继承,封装和多态.C#是一种现代的面向对象的语言.继承(inheritance):继承是一个面向对象的词语.说明,一个类(派生类)能分享,其它类(基类)的特征和行为.派生类和基类是"is a"的关系.base classes(基类):通常基类可以自己实例化,或被继承.派生类继承基类中的成员,被标记为protected或更大的权限.语法: class (derive class name):(base class name)例子:/基类public class Contact  /默认私有的字段  str

2、ing name;  string email;  string address;  /构造函数  public Contact()      / statements .    /属性   public string Name      get       return nam

3、e;     set          name = value;        public string Email      get          return email;  &

4、#160;     set          email = value;        public string Address      get          return address; 

5、;       set          address = value;      /派生类public class Customer : Contact  /自己的私有字段  string gender;  decimal income;  public Customer() 

6、;     / statements .  在上面的例子中,Customer 是 Contact的子类,不但,继承了父类的成员,name,email,address;还有自己的成员,gender,income.abstract classes(抽象类):抽象类是一种特殊的基类.除过普通的类成员,它们还有抽象的类成员.抽象类成员,是不能被实例化的方法和属性.所有直接从抽象类派生的类,必须实现抽象的方法和属性.抽象类不能被实例化.例子:/抽象类abstract public class Contact  pr

7、otected string name;  public Contact()      / statements.    /抽象方法  public abstract void generateReport();  /抽象属性  abstract public string Name      get;    set; 

8、; public class Customer : Contact  string gender;  decimal income;  int numberOfVisits;  public Customer()      / statements    public override void generateReport()      / un

9、ique report    public override string Name      get          numberOfVisits+;      return name;        set    

10、      name = value;      numberOfVisits = 0;       public class SiteOwner : Contact  int siteHits;  string mySite;  public SiteOwner()      / statemen

11、ts.    public override void generateReport()      / unique report    public override string Name      get          siteHits+;    &

12、#160; return name;        set          name = value;      siteHits = 0;      上面的例子,定义了三个类.一个抽象类,两个派生类.实现了父类的方法和属性."override"修饰符,实现了抽象类的

13、方法.    Calling Base Class Members(调用基类成员)派生类能调用基类成员,如果,成员的修饰符是"protected"或更大权限.在适当的上下文条件下,好像调用自己的成员一样.例子:abstract public class Contact  private string address;  private string city;  private string state;  private string zip; 

14、; public string FullAddress()      string fullAddress =      address + 'n' +      city + ',' + state + ' ' + zip;    return fullAddress;  public class

15、Customer : Contact  public string GenerateReport()      string fullAddress = FullAddress();    / do some other stuff.    return fullAddress;  上面的例子中,派生类调用基类的方法:FullAddress();基类的构造函数,可以被派生类调用,用base().例子:abstract

16、 public class Contact  private string address;  public Contact(string address)      this.address = address;  public class Customer : Contact  public Customer(string address) : base(address)    例子中,派生类没有address成

17、员,可以调用基类的构造函数.Hiding Base Class Members(隐藏基类成员)派生类可以和基类有同样名字的成员.这时,就会隐藏基类的成员.例子:abstract public class Contact  private string address;  private string city;  private string state;  private string zip;  public string FullAddress()   

18、60;  string fullAddress =      address + 'n' +      city + ',' + state + ' ' + zip;    return fullAddress;  public class SiteOwner : Contact  public string FullAddres

19、s()      string fullAddress;    / create an address.    return fullAddress;  在例子中,派生类和基类有同样的成员,FullAddress(),当调用时,基类的方法会被隐藏.尽管基类的成员被隐藏,仍然可以访问基类的成员,通过,base关键字,调用基类的引用.例子:abstract public class Contact  private st

20、ring address;  private string city;  private string state;  private string zip;  public string FullAddress()      string fullAddress =      address + 'n' +      c

21、ity + ',' + state + ' ' + zip;    return fullAddress;  public class SiteOwner : Contact  public string FullAddress()      string fullAddress = base.FullAddress();    / do some other stuff. 

22、   return fullAddress;  在例子中,派生类调用基类的成员,用base引用.visioning(版本)例子:using System;public class WebSite  public string SiteName;  public string URL;  public string Description;  public WebSite()      public WebS

23、ite( string strSiteName, string strURL, string strDescription )      SiteName  = strSiteName;    URL     = strURL;    Description = strDescription;    public override string T

24、oString()      return SiteName + ", " +       URL   + ", " +        Description;  public class Contact  public string address;  pu

25、blic string city;  public string state;  public string zip;  public string FullAddress()      string fullAddress =      address + 'n' +      city + ',' + state + &#

26、39; ' + zip;    return fullAddress;  public class SiteOwner : Contact  int   siteHits;  string name;  WebSite mySite;  public SiteOwner()      mySite = new WebSite();  

27、60; siteHits = 0;    public SiteOwner(string aName, WebSite aSite)      mySite = new WebSite(aSite.SiteName,                aSite.URL,      

28、         aSite.Description);     Name = aName;      public string Name      get          siteHits+;    &#

29、160; return name;        set          name = value;      siteHits = 0;      public class Test  public static void Main()  

30、60;   WebSite mySite = new WebSite("Le Financier", "http:/www.LeF",  "Fancy Financial Site");    SiteOwner anOwner = new SiteOwner("John Doe", mySite);    string address;   &#

31、160;anOwner.address = "123 Lane Lane"    anOwner.city  = "Some Town"    anOwner.state  = "HI"    anOwner.zip   = "45678"    address = anOwner.Ful

32、lAddress(); / Different Results    Console.WriteLine("Address: n0n", address);例子中,派生类用new修饰符,说明,和基类有同样名字的成员.sealed classed(密封类)密封类是不能被继承的类.为了避免从一个类中继承,就要生成密封类.例子:/密封类public sealed class CustomerStats  string gender;  decimal income;  int nu

33、mberOfVisits;  public CustomerStats()    public class CustomerInfo : CustomerStats / errorpublic class Customer  CustomerStats myStats; / okay例子中,密封类不能被继承. 封装(Encapsulation):封装是一个面向对象的概念,对外部世界,隐藏类的内部.封装优点:1.好的封装能减少耦合.2.类的内部的实现可以自由改变.3.一个类有更清楚的接口.Data Hiding(数据

34、隐藏):封装的一个最有用的形式是数据隐藏.一个类的数据表现一个对象的状态.修饰符支持封装:Private:只有类本身能存取.Protected:类和派生类可以存取.Internal:只有同一个项目中的类可以存取.Protected Internal:是Protected和Internal的结合. Public:完全存取.other Encapsulating Strategy:(其他封装策略)属性和索引器的目的是封装一个类的细节和给类的用户提供一个公共的接口.封装和继承的关系:封装的意思是包容(聚合),类与类之间的关系是"has a".一个类里面有另一个类.继承,类与类之间

35、的关系是"is a".多态(Polymorphism):就是怎样重载一个虚拟类.多态是面向对象的重要概念.Implementing Polymorphism(实现多态):例子:using System;public class WebSite  public string SiteName;  public string URL;  public string Description;  public WebSite()      pu

36、blic WebSite( string strSiteName, string strURL, string strDescription )      SiteName  = strSiteName;    URL     = strURL;    Description = strDescription;    public override

37、 string ToString()      return SiteName + ", " +        URL   + ", " +        Description;  abstract public class Contact  public virtu

38、al string UpdateNotify()      return "Web Site Change Notification"  public class Customer : Contact  public new string UpdateNotify()      return "This is to let you know your favorite site, Financial Tim

39、es,has been updated with new links"  public class SiteOwner : Contact  WebSite mySite;  public SiteOwner(string aName, WebSite aSite)      mySite = new WebSite(aSite.SiteName,          

40、      aSite.URL,                aSite.Description);    public new string UpdateNotify()      return "This is to let you know your site, " +

41、"n" +mySite.SiteName + ", has been added asa link to Financial Times."  public class Test  public static void Main()      WebSite leFin = new WebSite("Le Financier", "http:/www.LeF", "Fancy Finan

42、cial Site");    Contact Contacts = new Contact2;    Contacts0 = new SiteOwner("Pierre Doe", leFin);    Contacts1 = new Customer();    foreach (Contact poc in Contacts)      &#

43、160;   if (poc is SiteOwner)              Console.WriteLine("Message: 0n", (SiteOwner)poc).UpdateNotify();            else   

44、           Console.WriteLine("Message: 0n",  (Customer)poc).UpdateNotify();            在例子中,Contact类有个虚拟方法,有两个派生类分别实现.使用了"new"关键字.可以有更有效和优雅的方法,实现它,就是多态.例子:

45、using System;abstract public class Contact  public virtual string UpdateNotify()      return "Web Site Change Notification"  public class Customer : Contact  public override string UpdateNotify()      

46、;return "This is to let you know your favorite site, Financial Times,has been updated with new links"  public class SiteOwner : Contact  string siteName;  public SiteOwner(string sName)      siteName = sName;   

47、0;public override string UpdateNotify()      return "This is to let you know your site, " + "n" +siteName + ", has been added as a link to Financial Times."  public class Test  public static void Main()   

48、   Contact Contacts = new Contact2;    Contacts0 = new SiteOwner("Le Financier");    Contacts1 = new Customer();    foreach (Contact poc in Contacts)          Consol

49、e.WriteLine("Message: 0n",               poc.UpdateNotify();      例子中,派生类用"override"实现了多态.虚拟方法是允许多态工作的基类的方法.用"override"修饰符说明,能被派生类重载.虚拟方法和抽象方法的不同时,虚拟方法有实现,抽象方法没有.抽象方

50、法,隐式说明是虚拟,必须被重载;虚拟方法不必被重载.多态,必须是虚拟方法,而且,方法的签名必须一致,包括方法名称,参数,和参数类型.例子:abstract public class Contact  public virtual string UpdateNotify()     return "Web Site Change Notification"  public class Customer : Contact  public override string

51、 SendMail() / error  public override string UpdateNotify(int number) / error例子中,SendMail不是虚拟方法,故错误;UpdateNotify,带有不同的参数,故也错误.new 和 override 修饰符,都可以实现新的方法.但,new 实现的是派生类新的方法.例子:using System;abstract public class Contact  public virtual string UpdateNotify()    &

52、#160;return "Web Site Change Notification"  public class Customer : Contact  public new string UpdateNotify()      return "This is to let you know yourfavorite site, Financial Times,has been updated with new links"  publ

53、ic class SiteOwner : Contact  string siteName;  public SiteOwner(string sName)      siteName = sName;    public override string UpdateNotify()      return "This is to let you know your site, &quo

54、t; + "n" +siteName + ", has been added asa link to Financial Times."  public class Test  public static void Main()      Contact Contacts = new Contact2;    Contacts0 = new SiteOwner("Le Financier");&#

55、160;   Contacts1 = new Customer();    foreach (Contact poc in Contacts)          Console.WriteLine("Message: 0n",               po

56、c.UpdateNotify();      结果是:Message:This is to let you know your site,Le Financier, has been added asa link to Financial Times.Message: Web Site Change Notification例子中,Customer 用"new"实现新的方法,但是,在运行是不是多态.仍然调用基类的方法.Most-Derived Implementations(多重派生实现)Polymorphic P

57、roperties(多态的属性):C#允许,属性的多态实现.例子:using System;public class SiteStats  public int numberOfVisits = 0;abstract public class Contact  protected string name;  public virtual string Name      get        &#

58、160; return name;        set          name = value;      public class Customer : Contact  SiteStats myStats = new SiteStats();  public override string Name

59、      get          myStats.numberOfVisits+;      Console.WriteLine("Number of visits: 0",               m

60、yStats.numberOfVisits);      return name;        set          base.Name = value;      myStats.numberOfVisits = 0;      Console.WriteLine("Name: 0", Name);      public class Test  public static void Main()      Contact myContact = new Customer(); 

温馨提示

  • 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
  • 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
  • 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
  • 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
  • 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
  • 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
  • 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。

评论

0/150

提交评论