文档详情

面向对象程序设计实验四.doc

发布:2017-06-07约字共21页下载文档
文本预览下载声明
? 《面向对象程序设计》 实 验 报 告 ? ? 项目 实验四 继承和多态 班级 学号 姓名 时间 1. 实验目的 1.1. 理解继承和多态的概念。 1.2. 掌握new和base关键字的使用。 1.3. 理解对象的生命周期 1.4. 掌握虚拟方法和重载方法、抽象类和抽象方法、密封类和密封方法的使用。 2. 实验环境 2.1. Windows XP以上系统、Microsoft Visual Studio 2010 Express 3. 实验步骤 3.1. this和base 3.1.1. 请说明二者区别 this表示的是对当前对象的引用,其类型就是当前的类型。而base表示的是对基类对象的引用。 3.1.2. 修改P5_2例题中Run方法的(1 + load / Weight / 2),要求使用this.Speed和base.Speed替换;程序+结果 using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ConsoleApplication2 { class Program { static void Main(string[] args) { Truck t1 = new Truck(); Console.WriteLine(卡车速度{0}公里/小时, t1.Speed); Console.WriteLine(卡车行驶1000公里需要{0}小时, t1.Run(1000)); Automobile a1 = t1; Console.WriteLine(卡车速度{0}公里/小时, a1.Speed); Console.WriteLine(卡车行驶1000公里需要{0}小时, a1.Run(1000)); } } public class Automobile { protected float speed; public float Speed { get { return speed; } } private float weight; public float Weight { get { return weight; } set { weight = value; } } public float Run(float distance) { return distance / speed; } } public class Truck : Automobile { private float load; public float Load { get { return load; } set { load = value; } } public new float Speed { get { return speed / (1 + load / Weight / 2); } } public Truck() { load = 30; speed = 50; Weight = 15; } public new float Run(float distance) { //return (1 + load / Weight / 2) * base.Run(distance); return (base.Speed / this.Speed) * base.Run(distance); } } } 运行结果: 3.2. 隐藏和重载 3.2.1. 请说明二者区别 隐藏:如果派生类的成员方法隐藏了基类的成员方法,那么程序会根
显示全部
相似文档