欢迎来到天天文库
浏览记录
ID:48147091
大小:428.00 KB
页数:23页
时间:2020-01-16
《面向对象第五章继承和多态.ppt》由会员上传分享,免费在线阅读,更多相关内容在教育资源-天天文库。
1、第5章继承和多态5.1继承基类和派生类自顶向下的分解自底向上的抽象图形飞机汽车轮船交通工具5.1继承基类和派生类.NET类库5.1继承派生类的定义publicclassAutomobile{privatefloatspeed=100;publicfloatRun(floatdistance){returndistance/speed;}}publicclassBus:Automobile{}5.1继承派生类的使用publicstaticvoidMain(){Automobilea1=newAutomobile();a1.Run(1000);Busb1=newBus();b1
2、.Run(1000);a1=newBus();}例:P5_15.1继承隐藏基类成员publicclassAutomobile{protectedfloatspeed;protectedfloatweight;publicfloatRun(floatdistance){returndistance/speed;}}5.1继承隐藏基类成员publicclassCar:Automobile{publicnewfloatRun(floatdistance){return(1+weight/100)*distance/speed;}}5.1继承隐藏基类成员覆盖:根据声明类型决定成员调
3、用Automobilea1=newCar();a1.Run(1000);Cara2=newCar();a2.Run(1000);Automobile.RunCar.Run例:P5_25.1继承base关键字publicclassCar:Automobile(){...PublicvoidShowSpeed(){Console.WriteLine(“理想状态行驶1000千米需要{0}小时”,base.Run(1000));Console.WriteLine(“行驶1000千米需要{0}小时”,Run(1000));}Automobile.RunCar.RunpublicTru
4、ck(floatspeed):base(speed,15){load=30;}5.1继承base关键字publicTruck(floatspeed):base(speed){load=30;Weight=15;}publicAutomobile(){}publicAutomobile(floatspeed){this.speed=speed;}publicAutomobile(floatspeed,floatweight){this.speed=speed;this.weight=weight;}5.1继承对象的生命周期publicclassVehicle{}publicc
5、lassAutomobile:Vehicle{}publicclassCar:Automobile{}publicclassLimousine:Car{}newVehicle()newAutomobile()newCar()newLimousine()~Vehicle()~Automobile()~Car()~Limousine()例:P5_35.2多态性If(a1isBus)Console.WriteLine(“客车行驶1000千米需{0}小时”,((Bus)a1).Run(1000));elseif(a1isTruck)Console.WriteLine(“客车行驶10
6、00千米需{0}小时”,((Truck)a1).Run(1000));elseConsole.WriteLine(“客车行驶1000千米需{0}小时”,a1.Run(1000));问题:假设Bus和Truck类继承Automobile,并且都隐藏了Run方法,如何准确计算某汽车对象a1的行驶时间?5.2多态性基类:虚拟成员publicclassAutomobile{protectedfloatspeed;protectedfloatweight;publicvirtualfloatRun(floatdistance){returndistance/speed;}}5.2多态
7、性派生类:重载成员publicclassTruck:Automobile{privatefloatload;publicoverridefloatRun(floatdistance){returnbase.Run(1+(load+weight)/100);}}publicclassCar:Automobile{publicoverridefloatRun(floatdistance){return(1+weight/100)*distance/speed;}}5.2多态性重载:根据实际类型决定成员调用Automob
此文档下载收益归作者所有