我想知道是什么让一个类被称为抽象类。我相信,抽象关键字肯定是一个类,但是如果去掉关键字,那么我们就可以创建类的实例。
也就是说,抽象类的特点是什么。
提前致谢。
-戒日
最佳答案
与纯实现类不同,抽象类在现实世界中不会形成具体对象。 顾名思义,抽象类包含/定义需要独立重用/定义的相关对象的共同行为在所有相关对象中。
以鸟类为例。如果您正在编写一个与鸟类有关的程序,那么您将首先拥有一个抽象基类 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/