第三讲类和结构C#详解.ppt

  1. 1、原创力文档(book118)网站文档一经付费(服务费),不意味着购买了该文档的版权,仅供个人/单位学习、研究之用,不得用于商业用途,未经授权,严禁复制、发行、汇编、翻译或者网络传播等,侵权必究。。
  2. 2、本站所有内容均由合作方或网友上传,本站不对文档的完整性、权威性及其观点立场正确性做任何保证或承诺!文档内容仅供研究参考,付费前请自行鉴别。如您付费,意味着您自己接受本站规则且自行承担风险,本站不退款、不进行额外附加服务;查看《如何避免下载的几个坑》。如果您已付费下载过本站文档,您可以点击 这里二次下载
  3. 3、如文档侵犯商业秘密、侵犯著作权、侵犯人身权等,请点击“版权申诉”(推荐),也可以打举报电话:400-050-0827(电话支持时间:9:00-18:30)。
查看更多
* using System; public class Animal { public Animal() { } public void sleep() { } public bool IsHungry = true; public virtual void Eat() { Console.WriteLine(Eat something); } } public class Elephant:Animal { public int CarryCapacity; public override void Eat() { Console.WriteLine(Eat grass); } } public class Mouse:Animal { public override void Eat() { Console.WriteLine(Eat rice); } } public class Cat:Animal { public void StalkPrey() { } public override void Eat() { Console.WriteLine(Eat mouse); } } public class WildLife { public WildLife() { Elephant myElephant = new Elephant(); Mouse myMouse = new Mouse(); Cat myCat = new Cat(); FeedingTime(myElephant); FeedingTime(myMouse); FeedingTime(myCat); } public void FeedingTime(Animal someCreature) { if (someCreature.IsHungry) { someCreature.Eat(); } } static void Main() { WildLife w = new WildLife(); Console.ReadLine(); } } * 不同的几何图形,计算面积的方法是不一样的。所以不能在shape类中实现方法。所以把方法定义为抽象方法,让各个子类去自己实现。 * 抽象方法肯定是虚方法,所以一定要去覆盖这个抽象方法。 using System; public abstract class Animal { public abstract void sleep(); } public class Elephant:Animal { public override void sleep() { Console.WriteLine(Elephant sleep); } } public class Mouse:Animal { public override void sleep() { Console.WriteLine(Mouse sleep); } } public class Cat:Animal { public override void sleep() { Console.WriteLine(Cat sleep); } } public class WildLife { public WildLife() { Elephant myElephant = new Elephant(); Mouse myMouse = new Mouse(); Cat myCat = new Cat(); myElephant.sleep(); myMouse.sleep(); myCat.sleep(); } static void Main() { WildLife w = new WildLife(); Console.ReadLine(); //Animal a = new Animal(); //a.sleep(); } } 多态(续) 【例2】重写基类的方法。 多态(续) 2、隐藏基类的方法 在扩充类中,可以使用new关键字来隐藏基类的方法,即使用一个完全不同的方法取代旧的方法。 与方法重写不同的是,使用new关键字时并不要求基类中的方法声明为virtual,只要在扩充类的方法前声明为new,就可以隐藏基类的方法。 3.在扩充类直接调用基类的方法 使用base关键字 * 关键字 override Class Base {  // 成员变量 int base

文档评论(0)

钱缘 + 关注
实名认证
内容提供者

该用户很懒,什么也没介绍

1亿VIP精品文档

相关文档