概念:用 abstract 修飾符來(lái)指示某個(gè)類僅用作其他類的基類,而不用于自行進(jìn)行實(shí)例化埠戳。 標(biāo)記為抽象的成員必須由派生自抽象類的非抽象類來(lái)實(shí)現(xiàn)。
1. 抽象類特點(diǎn):
- 抽象類不能實(shí)例化诫钓。
- 抽象類可能包含抽象方法和訪問(wèn)器幔睬。
- 無(wú)法使用 sealed 修飾符來(lái)修改抽象類,因?yàn)閮蓚€(gè)修飾符的含義相反旧噪。詳細(xì)請(qǐng)見sealed代碼案例
- 派生自抽象類的非抽象類吨娜,必須包含全部已繼承的抽象方法和訪問(wèn)器的實(shí)際實(shí)現(xiàn)。
2. 抽象方法特點(diǎn):
- 抽象方法是隱式的虛擬方法舌菜。
- 只有抽象類中才允許抽象方法聲明萌壳。
- 由于抽象方法聲明不提供實(shí)際的實(shí)現(xiàn),因此沒(méi)有方法主體日月;方法聲明僅以分號(hào)結(jié)尾袱瓮,且簽名后沒(méi)有大括號(hào) ({ })。 例如:
public abstract void MyMethod();
實(shí)現(xiàn)由方法 override 提供爱咬,它是非抽象類的成員尺借。
3.virtual
class TestClass
{
public class Shape
{
public const double PI = Math.PI;
protected double x, y;
public Shape()
{
}
public Shape(double x, double y)
{
this.x = x;
this.y = y;
}
public virtual double Area()
{
return x * y;
}
}
public class Circle : Shape
{
public Circle(double r) : base(r, 0)
{
}
public override double Area()
{
return PI * x * x;
}
}
class Sphere : Shape
{
public Sphere(double r) : base(r, 0)
{
}
public override double Area()
{
return 4 * PI * x * x;
}
}
class Cylinder : Shape
{
public Cylinder(double r, double h) : base(r, h)
{
}
public override double Area()
{
return 2 * PI * x * x + 2 * PI * x * y;
}
}
static void Main()
{
double r = 3.0, h = 5.0;
Shape c = new Circle(r);
Shape s = new Sphere(r);
Shape l = new Cylinder(r, h);
// Display results.
Console.WriteLine("Area of Circle = {0:F2}", c.Area());
Console.WriteLine("Area of Sphere = {0:F2}", s.Area());
Console.WriteLine("Area of Cylinder = {0:F2}", l.Area());
}
}
/*
Output:
Area of Circle = 28.27
Area of Sphere = 113.10
Area of Cylinder = 150.80
*/