抽象类的特征

Har*_*sha 2 c# oop

我想知道是什么使一个类被称为抽象类.我相信,abstract关键字肯定会创建一个类,但如果取出关键字,那么我们就可以创建该类的实例.

换句话说,抽象类的特征是什么.

提前致谢.

-Harsha

thi*_*eek 8

与纯实现类不同,抽象类不会在现实世界中形成具体对象.抽象作为名称暗示他们持有/定义相关对象的共同行为,这些行为需要在所有相关对象中独立地重复使用/定义.

以鸟类为例.如果你正在编写一个与鸟类有关的程序,那么你将首先得到一个抽象基类作为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)