1.定义
(1)继承:向子类中添加父类没有的成员,子类对父类的横向扩展
(2)重写:纵向扩展,成员没有增加,但成员的版本增加了
(3)多态:基于重写的
2.重写案例(父类的成员需要是public或者protected)
class Program
{
static void Main(string[] args)
{
Car car1 = new Car();
car1.Run();
// Car is running!
Vehicle car2 = new Car();
car2.Run();
// Car is running!
var v = new Vehicle();
v.Run();
// I'm running!
}
}
class Vehicle
{
public virtual void Run()
{
Console.WriteLine("I'm running!");
}
}
class Car : Vehicle
{
public override void Run()
{
Console.WriteLine("Car is running!");
}
}
3.继承案例
class Program
{
static void Main(string[] args)
{
Car car1 = new Car();
car1.Run();
// Car is running!
Vehicle car2 = new Car();
car2.Run();
// I'm running!
Vehicle v3 = new Vehicle();
v3.Run();
// I'm running!
}
}
class Vehicle
{
public void Run()
{
Console.WriteLine("I'm running!");
}
}
class Car : Vehicle
{
public void Run()
{
Console.WriteLine("Car is running!");
}
}
学习用途,侵权立删;
参考文献