using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Vehicles
{
class Car : Vehicle//汽车类继承车辆类
{
public void Accelerate()//加速
{
Console.WriteLine("Accelerating");
}
public void Brake()//刹车
{
Console.WriteLine("Braking");
}
public new void Drive()//new关键字覆盖基类的drive
{
Console.WriteLine("motoring");
}
}
}
________________________________________
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Vehicles
{
class Airplane:Vehicle//飞机继承车辆类
{
public void TakeOff()//关闭飞机
{
Console.WriteLine("Taking off");
}
public void Land()//着陆
{
Console.WriteLine("Landing");
}
public new void Drive()//new关键字覆盖基类的drive
{
Console.WriteLine("Flying");
}
}
}
__________________________________________
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Vehicles
{
class Vehicle//车辆类
{
public void StartEngine(String noiseToMakeWhenStarting)
{
Console.WriteLine("Starting engine:{0}", noiseToMakeWhenStarting);
}
public void StopEngine(string noiseToMakeWhenStopping)
{
Console.WriteLine("Stopping engine:{0}", noiseToMakeWhenStopping);
}
public void Drive()
{
Console.WriteLine("Default implementation of the drive method");
}
}
}
________________________________________________
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();//派生类的drive
myplane.Land();
myplane.StartEngine("Whirr");
Console.WriteLine("\nJourney by car:");
Car myCar = new Car();
myCar.StartEngine("Brm brm");
myCar.Accelerate();
myCar.Drive();//派生类的drive
myCar.Brake();
myCar.StartEngine("phut phut");
Console.WriteLine("\nTesting polymorphism");
Vehicle v =(Vehicle) myCar;//车辆类对象v强制转换为基类的对象
v.Drive();//car类的drive(调用的是基类的drive)
v =(Vehicle) myplane;//车辆类对象v强制转换为基类的对象
v.Drive();//airplane的drive(调用的是基类的drive)
}
static void Main()
{
try
{
DoWork();
}
catch (Exception ex)
{
Console.WriteLine("Exception: {0}", ex.Message);
}
Console.ReadKey();
}
}
}
————————————————————————————
如图,上面两个drive是派生类的,下面两个drive是基类的,因为通过了基类的强制转换,已经是基类的对象了。所以访问的是基类的drive