C#的多态性

new与overide

View Code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;

namespace ConsoleApplication2
{
class Program
{
// Define the base class
class Car
{
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.");
}
}

/// <summary>
/// new and overide
/// </summary>
/// <param name="args"></param>
static void Main(string[] args)
{
Car[] cars
= new Car[3];
cars[
0] = new Car();
cars[
1] = new ConvertibleCar();
cars[
2] = new Minivan();
foreach (Car vehicle in cars)
{
System.Console.WriteLine(
"Car object: " + vehicle.GetType());
vehicle.DescribeCar();
System.Console.WriteLine(
"----------");
}
Console.ReadKey();
}

}

}

  上面,程序最后的第二个执行.并没有执行 ConvertibleCar()中的  System.Console.WriteLine("A roof that opens up.");

而选择了基类的中的方法.原因是因为用了new;同样,由于使用了overide.而让其无论如何都执行子类的方法.

overide与overload

重载(Overload)
重载---类中定义的方法可能有不同的版本
public book withdraw(double amt,string name)
public double withdraw(double amt)
特点:方法名必须相同
参数列表必须不相同
返回值类型可以不相同

虚拟函数

声明虚方法
使用virtual关键字 public virtual bool withdraw(...)
调用虚方法,运行时将确定调用对象是什么类的实例,并调用适当的覆写的方法。
虚方法可以有实现体

覆写(overwrite)
子类为满足自己的需要来重复定义某个方法的不同实现--覆写
通过使用关键字override来覆写
public override bool withdraw()
只有虚方法和抽象方法才能覆写

特点:

相同的方法名称
相同的参数列表
相同的返回值类

抽象方法:

必须被派生类覆写的方法
可以看成是没有实现体的虚方法
如果类包含抽象方法,那么类就必须定义为抽象类,不论是否还包含其他一般方法
public abstract bool withdraw()

posted on 2011-08-07 21:20  HelyCheng  阅读(101)  评论(0)    收藏  举报

导航