class Program
{
static void Main(string[] args)
{
//有一个交通工具类Vehicle,将它作为基类派生小车类Car、卡车类Truck和轮船类Boat,定义这些类并定义一个虚函数用来显示各类信息。
Vehicle vehicle = new Vehicle("交通工具", 8, 8);
Truck truck = new Truck("东风", 18, 18);
Car car = new Car("小汽车", 28, 28);
Boat boat = new Boat("轮船", 38, 38);
truck.ShowMsg();
car.ShowMsg();
boat.ShowMsg();
vehicle.ShowMsg();
}
}
class Boat:Vehicle
{
public Boat(string _name, int _jiage, int _speed)
: base(_name, _jiage, _speed)
{
}
public override void ShowMsg()
{
Console.WriteLine("轮船{0},价格{1},速度{2}", Name, Jiage, Speed);
}
}
class Car:Vehicle
{
public Car(string _name, int _jiage, int _speed)
: base(_name, _jiage, _speed)//base 有参数就执行父类的有参数构造函数 没有就默认执行父类没有参数的构造函数
{
}
public override void ShowMsg()
{
Console.WriteLine("汽车{0},价格{1},速度{2}", Name, Jiage, Speed);
}
}
class Truck:Vehicle
{
public Truck(string _name, int _jiage, int _speed)
: base()
{
this.Name = _name;
this.Jiage = _jiage;
this.Speed = _speed;
}
public Truck(string _name, int _jiage, int _speed)
: base(_name, _jiage, _speed)
{
}
public override void ShowMsg()
{
Console.WriteLine("卡车{0},价格{1},速度{2}", this.Name, this.Jiage, this.Speed);
}
}
class Vehicle
{
private string name = "1";
private int jiage;
private int speed;
public string Name
{
get { return name; }
set { name = value; }
}
public int Jiage
{
get { return jiage; }
set
{
if (value > 0)
{
jiage = value;
}
else
{
Console.WriteLine("价格有误!");
}
}
}
public int Speed
{
get { return speed; }
set { speed = value; }
}
public Vehicle(string _name, int _jiage, int _speed)
{
this.name = _name;
this.jiage = _jiage;
this.speed = _speed;
}
public Vehicle()
{
this.ShowMsg();
}
public virtual void ShowMsg()
{
Console.WriteLine("交通工具{0},售价{1},速度{2}", Name, Jiage, Speed);
}
}