c# - 抽象类的特点

标签 c# oop

我想知道是什么让一个类被称为抽象类。我相信,抽象关键字肯定是一个类,但是如果去掉关键字,那么我们就可以创建类的实例。

也就是说,抽象类的特点是什么。

提前致谢。

-戒日

最佳答案

与纯实现类不同,抽象类在现实世界中不会形成具体对象。 顾名思义,抽象类包含/定义需要独立重用/定义的相关对象的共同行为在所有相关对象中。

以鸟类为例。如果您正在编写一个与鸟类有关的程序,那么您将首先拥有一个抽象基类 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();
    }
}

关于c# - 抽象类的特点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2849056/

相关文章:

c# - XmlWriter 设计背后的 OOP 推理是什么?

c++ - 确定在 C++ 代码中调用了哪些复制构造函数

c# - 来自引用的 .NET Standard 项目的多个 DLL

c# - 使用数组在 C# 中进行数据驱动测试

javascript - 如何使用 Javascript 标记从对象内选择的下拉列表

c++ - 如何从 C++ 类中的排序调用比较器函数

c# - 处理 CancellationTokenRegistration

C# 静态成员在构造函数中初始化后获取 null

c# - 如何在 Debug模式下浏览所有 session 变量?

c++ - 为什么 PlayerController "own"是偏航俯仰和滚动,而 Character "owns"是它的位置?