设计一个交通工具类Vehicle,包含的数据成员有车轮个数wheels和车重weight。以及带有这两个参数的构造方法,具有Run方法,Run中方法输出running字样。小车类Car是它的子类,其中增加了数据成员车载人数passenger_load。Car类中有带参数的构造方法,重写Run方法:输出Car is running。并重写ToString()方法:显示car中信息(显示车轮数、车重、车载人数)。最后编写主方法,定义car的对象,并调用Run方法,以及显示car中信息。
关键知识点:
虚函数:virtual? 重写:override? 继承后构造基类:base
具体实现代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 |
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ConsoleApplication6 { class Program { static void Main(string[] args) { Car car = new Car(4, 10000.0, 5); car.Run(); car.ToString(); Console.Read(); } } class Vehicle { private int wheels; private double weight; public int Wheels { set { wheels = value; } get { return wheels; } } public double Weight { set { weight = value; } get { return weight; } } public Vehicle(int wheels, double weight) { this.wheels = wheels; this.weight = weight; } public virtual void Run() { Console.WriteLine("running"); } } class Car : Vehicle { private int passenger_load; public Car(int wheels, double weight, int passenger_load) :base(wheels, weight) { this.passenger_load = passenger_load; } public override void Run() { Console.WriteLine("Car is running"); } public override string ToString() { Console.WriteLine("车轮数{0},车重{1},车载人数{2}", Wheels, Weight, passenger_load); return base.ToString(); } } } |
运行结果:
