作者: 许庭洲 时间: 2014-4-24 20:40
// Define the base class
class Car
{
public int wheels;//公有成员:轮子个数
protected float weight; //保护成员:重量
public Car()
{
// ......
}
public Car(int w,float g)
{
wheels = w;
weight = g;
}
public virtual void DescribeCar()
{
System.Console.WriteLine("Four wheels and an engine.");
}
}
// Define the derived classes
class ConvertibleCar : Car
{
public new virtual void DescribeCar()
{
base.DescribeCar();
System.Console.WriteLine("A roof that opens up.");
}
}
class Minivan : Car
{
public override void DescribeCar()
{
base.DescribeCar();
System.Console.WriteLine("Carries seven people.");
}
}
现在可以编写一些代码来声明这些类的实例,并调用它们的方法以便对象能够描述其自身:
public static void TestCars1()
{
Car car1 = new Car();
car1.DescribeCar();
System.Console.WriteLine("----------");
ConvertibleCar car2 = new ConvertibleCar();
car2.DescribeCar();
System.Console.WriteLine("----------");
Minivan car3 = new Minivan();
car3.DescribeCar();
System.Console.WriteLine("----------");
}
正如预期的那样,输出类似如下所示:
Four wheels and an engine.
----------
Four wheels and an engine.
A roof that opens up.
----------
Four wheels and an engine.
Carries seven people. 作者: czwanglei 时间: 2014-4-25 21:49
首先把三个,每一个理解透彻了,慢慢就会理解之间的区别了。