Override 重写:
含义:永远调用的是实例的最新版本(属性也可以重写)
可见:
只有对子类可见的父类成员可以重写,具体说就是 protected 和 public。例如子类能继承父类 private 的成员,但无法访问,即不可见、不可重写。
class Demo_Polymorphisms
{
public void test()
{
Demo29_Vehicle vehicle = new Demo29_RaceCar();
vehicle.Run();// Car is running
(vehicle as Demo29_RaceCar).Run(); // RaceCar is running
Console.WriteLine(vehicle.Speed); // 110
}
}
class Demo29_Vehicle
{
private int _speed = 100;
public virtual int Speed
{
get { return _speed; }
set { _speed = value; }
}
public virtual void Run()
{
Console.WriteLine("Vehicle is running.");
}
}
class Demo29_Car : Demo29_Vehicle
{
private int speed_bias = 10;
public override void Run()
{
Console.WriteLine("Car is running.");
}
public override int Speed { get => base.Speed + speed_bias; set => base.Speed = value; }
}
class Demo29_RaceCar : Demo29_Car
{
public void Run()
{
Console.WriteLine("RaceCar is running.");
}
}