与纯实现类不同,抽象类不会在现实世界中形成具体对象.抽象作为名称暗示他们持有/定义相关对象的共同行为,这些行为需要在所有相关对象中独立地重复使用/定义.
以鸟类为例.如果你正在编写一个与鸟类有关的程序,那么你将首先得到一个抽象基类作为Bird,每只鸟都来自抽象基类Bird.请注意,抽象类BIRD并不代表具体的真实世界对象,而是一种相关对象,即鸟类!
让我们从类图开始,然后是一些代码.
alt text http://ruchitsurati.net/files/birds.png
public abstract class Bird
{
protected string Name = string.Empty;
public Bird(string name)
{
this.Name = name;
}
public virtual void Fly()
{
Console.WriteLine(string.Format("{0} is flying.", this.Name));
}
public virtual void Run()
{
Console.WriteLine(string.Format("{0} cannot run.", this.Name));
}
}
public class Parrot : Bird
{
public Parrot() : base("parrot") { }
}
public class Sparrow : Bird
{
public Sparrow() : base("sparrow") { }
}
public class Penguin : Bird
{
public Penguin() : base("penguin") { }
public override void Fly()
{
Console.WriteLine(string.Format("{0} cannot fly. Some birds do not fly.", this.Name));
}
public override void Run()
{
Console.WriteLine(string.Format("{0} is running. Some birds do run.", this.Name));
}
}
class Program
{
static void Main(string[] args)
{
Parrot p = new Parrot();
Sparrow s = new Sparrow();
Penguin pe = new Penguin();
List<Bird> birds = new List<Bird>();
birds.Add(p);
birds.Add(s);
birds.Add(pe);
foreach (Bird bird in birds)
{
bird.Fly();
bird.Run();
}
Console.ReadLine();
}
}
Run Code Online (Sandbox Code Playgroud)