案例:
主要有Vehicle.cs Airplane.cs Car.cs 3个类。
Car和Airplane都继承与Vehicle类。Vehicle中Drive为虚方法,可在子类中重写,父类引用子类对象,并在car中重写了Drive方法。
class Vehicle
{
public void StartEngine(string noiseToMakeWhenStaring)
{
Console.WriteLine("starting engine:{0}",noiseToMakeWhenStaring);
} public void StopEngine(string noiseToMakeWhenStopping)
{
Console.WriteLine("stopping engine:{0}",noiseToMakeWhenStopping);
} public virtual void Drive()
{
Console.WriteLine("Default Drive method");
}
}
class Airplane :Vehicle
{
public void Takeoff(){
Console.WriteLine("take off");
}
public void Land()
{
Console.WriteLine("land");
}
}
class Car:Vehicle
{
public void SpeedUp()
{
Console.WriteLine("SpeedUp");
} public void SpeedDown()
{
Console.WriteLine("SpeedDown");
} public override void Drive()//重写父类Drive中的方法
{
Console.WriteLine("Motoring");
}
}
Program.cs
using System; namespace Vehicles
{
class Program
{
static void DoWork()
{
Console.WriteLine("Journey by airplane:");
Airplane myplane = new Airplane();
myplane.StartEngine("Contact");
myplane.Takeoff();
myplane.Drive();
myplane.Land();
myplane.StopEngine("whirr"); Console.WriteLine("\nJourney by car");
Car mycar = new Car();
mycar.StartEngine("gogo");
mycar.SpeedUp();
mycar.Drive();
mycar.SpeedDown();
mycar.StopEngine("stop"); Console.WriteLine("\nTest");
Vehicle v = mycar;//父类引用子类对象;
v.Drive(); //运行为子类中重写的方法
v = myplane;
v.Drive();
} static void Main()
{
try
{
DoWork();
}
catch (Exception ex)
{
Console.WriteLine("Exception: {0}", ex.Message);
}
Console.ReadKey();
}
}
}
注意:
在program中父类可以引用子类对象复制,类的赋值的原则是,子类型可以赋值给父类型,反之需要进行强制转换。在子类中是用override可以重构父类的方法,代码执行过程中,会引用子类中重构的父类方法。