抽象类包含抽象方法,这些方法由派生类实现。派生类具有更特殊的功能。
以下示例显示了C#中抽象类的用法。
using System;
namespace Demo {
   abstract class Shape {
      public abstract int area();
   }
   class Rectangle: Shape {
      private int length;
      private int width;
      public Rectangle( int a = 0, int b = 0) {
         length = a;
         width = b;
         Console.WriteLine("Length of Rectangle: "+length);
         Console.WriteLine("Width of Rectangle: "+width);
      }
      public override int area () {
         return (width * length);
      }
   }
   class RectangleTester {
      static void Main(string[] args) {
         Rectangle r = new Rectangle(14, 8);
         double a = r.area();
         Console.WriteLine("Area: {0}",a);
         Console.ReadKey();
      }
   }
}输出结果
Length of Rectangle: 14 Width of Rectangle: 8 Area: 112
我们上面的抽象类是-
abstract class Shape {
   public abstract int area();
}以下是有关抽象类的规则。
您不能创建抽象类的实例
您不能在抽象类之外声明抽象方法
当一个类被声明为密封的时,它不能被继承,抽象类也不能被声明为密封的。