抽象类

在C#中,C#允许把类和函数声明为abstract。

抽象类不能实例化,抽象类可以包含普通函数和抽象函数,抽象函数就是只有函数定义没有函数体。显然,抽象函数本身也是虚拟的virtual(只有函数定义,没有函数实现)。

类是一个模板,那么抽象类就是一个不完整的模板,我们不能使用不完整的模板去构造对象。

先声明一个抽象类Total:

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 
 6 namespace Abstract
 7 {
 8     abstract class Total
 9     {
10         private float speed;
11         public void Eat()
12         {
13         }
14 
15         public abstract void Fly();
16         //一个类中如果有一个抽象方法,那么这个类必须被定义为一个抽象类  一个抽象类就是一个不完整的模板,我们不可以用抽象类去实例化构造对象
17     }
18 }

然后再声明这个抽象类的子类Bird:

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 
 6 namespace Abstract
 7 {
 8     class Bird:Total//我们成立一个抽象类的时候必须去实现抽象方法,给出方法体
 9     {
10         public override void Fly()//使用抽象方法时需要在返回类型前添加 override 复写
11         {
12             Console.WriteLine("鸟在飞");
13         }
14     }
15 }

我们在Program类中实现抽象类中的方法:

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 
 6 namespace Abstract
 7 {
 8     class Program
 9     {
10         static void Main(string[] args)
11         {
12             Total b = new Bird();//我们可以利用抽象类去声明对象,但我们必须利用抽象类的子类去构造  Bird b=new Bird();
13             b.Fly();
14             Console.ReadKey();
15         }
16 
17         
18     }
19 }
原文地址:https://www.cnblogs.com/jc-1997/p/6131717.html