本帖最后由 许庭洲 于 2014-4-30 16:41 编辑
//多态性通过派生类重载基类中的虚函数型方法来实现
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
using System;
class Vehicle//定义汽车类
{
public int wheels;//公有成员:轮子个数
protected float weight;//保护成员;重量
public Vehicle(int w,float g)
{
wheels=w;
weight=g;
}
public virtual void Speak()
{
Console.WriteLine("the w vehicle is speaking!");
}
};
class Car:Vehicle//定义轿车类
{
int passengers;//私有成员:乘客数
public Car(int w,float g,int p):base(w,g)
{
wheels=w;
weight=g;
passengers=p;
}
public override void Speak()
{
Console.WriteLine("the Car vehicle is speaking: Di-di!");
}
}
class Truck:Vehicle//定义卡车类
{
int passengers;//私有成员:乘客数
float load;//私有成员:载重量
public Truck(int w,float g,int p,float l):base(w,g)
{
wheels=w;
weight=g;
passengers=p;
load=1;
}
public override void Speak()
{
Console.WriteLine("the Truckvehicle is speaking: Ba-ba!");
}
}
class Test
{
public static void Main()
{
Vehicle v1=new Vehicle();
Car c1=new Car(4,2,5);
Truck t1=new Truck(6,5,3,10);
v1.Speak();
v1=c1;
v1.Speak();
c1.Spreak();
v1=t1;
v1.Speak();
t1.Speak();
}
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
1.Vehicle类中的Speak方法被声明为虚方法,那么在派生类中就可以重新定义此方法;
2.在派生类Car和Truck中分别重载了Speak方法,派生类中的方法原型和基类中的方法原型必须完全一致。
3.在Test类中,创建了Vehicle类实例v1,并且先后指向Car类的实例c1和Truck类的实例t1。
4.运行改程序,结果因该是:
The Vehicle is speaking!
The Car is speaking: Di-di!
The Car is speaking: Di-di!
The truck is speaking: Ba-ba!
The truck is speaking: Ba-ba!
|