《第5章继承和多态.ppt》由会员分享,可在线阅读,更多相关《第5章继承和多态.ppt(16页珍藏版)》请在三一文库上搜索。
1、1,第5章 继承和多态,继承,基类和派生类 自顶向下的分解 自底向上的抽象,2,图形,飞机,汽车,轮船,交通工具,继承,基类和派生类 .NET类库,3,继承,基类和派生类,4,public class Automobile private float speed = 100; public float Run(float distance) return distance/speed; public class Bus : Automobile ,Automobile a1 = new Automobile(); a1.Run(1000); Bus b1 = new Bus(); b1.Run
2、(1000);,继承,对象的生命周期 构造 析构,5,public class Vehicle public class Automobile : Vehicle public class Car : Automobile public class Limousine : Car ,new Vehicle(),new Automobile(),new Car(),new Limousine(),Vehicle(),Automobile(), Car(),Limousine(),多态性,基类:普通成员 派生类:覆盖成员,6,public class Automobile protected fl
3、oat speed; protected float weight; public float Run(float distance) return distance/speed; ,public class Car : Automobile public new float Run(float distance) return (1+weight/100) * distance/speed; ,多态性,覆盖:根据声明类型决定成员调用,7,Automobile a1 = new Truck(); a1.Run(1000); Car a2 = new Car(); a2.Run(1000);,A
4、utomobile.Run,Car.Run,多态性,基类:虚拟成员,8,public class Automobile protected float speed; protected float weight; public virtual float Run(float distance) return distance/speed; ,多态性,基类:虚拟成员 派生类:重载成员,9,public class Truck : Automobile private float load; public override float Run(float distance) return base
5、.Run(1+(load+weight)/100); ,public class Car : Automobile public override float Run(float distance) return (1+weight/100) * distance/speed; ,多态性,重载:根据实际类型决定成员调用,10,Automobile a1 = new Car(); a1.Run(1000); Automobile a2 = new Truck(); a2.Run(1000);,Car.Run,Truck.Run,多态性,抽象类和抽象方法,11,public abstract cl
6、ass Automobile protected float speed; protected float weight; public abstract float Run(float distance); ,Automobile a1 = new Automobile();,多态性,抽象类和抽象方法,12,public class Truck : Automobile private float load; ,多态性,抽象类和抽象方法,13,public class Truck : Automobile private float load; public override float R
7、un(float distance) return base.Run(1+(load+weight)/100); ,多态性,密封类和密封方法,14,public class BigTruck : Truck ,public sealed class Truck : Automobile private float load; public override float Run(float distance) return base.Run(1+(load+weight)/100); ,多态性,密封类和密封方法,15,public class BigTruck : Truck public ov
8、erride float Run(float distance) return base.Run(1+2*(load+weight)/100); ,public class Truck : Automobile private float load; public sealed float Run(float distance) return base.Run(1+(load+weight)/100); ,16,本章习题,简述public, protected, private关键字在继承中的作用。 简述覆盖和重载的区别,以及它们各自的适用场合。 属性、索引函数和构造函数可否被虚拟和重载? 试说说图书馆管理系统中可能存在哪些虚拟和重载的情况?,