在C#中,C#容许把类和函数声明为abstract。ide
抽象类不能实例化,抽象类能够包含普通函数和抽象函数,抽象函数就是只有函数定义没有函数体。显然,抽象函数自己也是虚拟的virtual(只有函数定义,没有函数实现)。函数
类是一个模板,那么抽象类就是一个不完整的模板,咱们不能使用不完整的模板去构造对象。spa
先声明一个抽象类Total:code
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类中实现抽象类中的方法:blog
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 }