using System;
namespace ConsoleApplication2
{
/// <summary>
/// Class1 的摘要说明。
/// </summary>
class Class1
{
/// <summary>
/// 应用程序的主入口点。
/// </summary>
[STAThread]
static void Main(string[] args)
{
//
// TODO: 在此处添加代码以启动应用程序
//
vehicle myvc=new vehicle();
car mycar=new car(4,2,5);
truck mytk=new truck(6,5,3,10);
myvc.speeking();
myvc=mycar;
myvc.speeking();
mycar.speeking();
myvc=mytk;
myvc.speeking();
mytk.speeking();
Console.ReadLine();
}
}
//class vehicle
class vehicle
{
public int wheels;
protected float weight;
public vehicle()
{
}
public vehicle(int w,float g)
{
this.wheels=w;
this.weight=g;
}
public virtual void speeking()
{
Console.WriteLine("the vehicle is speeking!"+this.wheels+this.weight);
}
}
//class car
class car:vehicle
{
private int passengers;
public car(int w,float g,int p):base(w,g)
{
wheels=w;
weight=g;
this.passengers=p;
}
public override void speeking()
{
Console.WriteLine("the car speeking!"+this.wheels+this.weight+this.passengers);
}
}
//class
class truck:vehicle
{
int passengers;
float load;
public truck(int w,float g,int p,float l):base(w,g)
{
this.wheels=w;
this.weight=g;
this.passengers=p;
this.load=l;
}
public override void speeking()
{
Console.WriteLine("the truck speeking!"+this.wheels+this.weight+this.passengers+this.load);
}
}
}
编译时多态:通过重载来实现的,虚类vechile通过子类的继承实现多态,子类再付给Base类就可以实现多态的效果了。
浙公网安备 33010602011771号