一个类加上修饰符abstract之后,就表明它自己是不完整的,只能当做其它类的基类。抽象可以理解为从多个对象提取公共部分,并把他们并入到单独的抽象类中实现。
抽象类中可以指定抽象成员(abstrct member),抽象类可以不含抽象方法。抽象方法不能是静态的,含有抽象方法的类一定是抽象类,也一定要加abstract类修饰符。 抽象(abstract)方法在逻辑上类似于虚方法,只是不能像虚方法那样被调用。
含有抽象方法的抽象类的子类必须覆盖并实现(直接使用override)该方法,即抽象成员在派生类中必须被实例化,或者组合使用abstract override使之继续抽象,或者不提供任何覆盖和实现。后两者的行为是一样的。
public abstract class Shape //抽象类
{
protected string color;
public Shape(string color)
{
this.color = color;
}
public string getColor() //非抽象方法
{
return color;
}
public abstract double getArea() ; //抽象成员
}
public class Circle : Shape
{
private double radious;
public Circle(string color, double radious) : base(color) //用参数color调用父类的构造函数
{
this.radious = radious;
}
public override double getArea() //抽象方法在派生类中被实例化
{
return System.Math.PI * radious * radious;
}
}
public class Square: Shape
{
private double sideLength;
public Square(string color, double sideLength): base(color) //用参数color调用父类的构造函数
{
this . sideLength = sideLength;
}
public override double getArea() //抽象方法在派生类中被实例化
{
return sideLength * sideLength;
}
}
public class Example()
{
static void Main()
{
Shape myCircle =new Circle ("red" ,3);
Shape mySquare=new Square ("Green",4);
Console.WriteLine(myCircle.getColor(),myCircle.getArea());
Console.WriteLine (mySquare.getColor(),mySquare.getArea());
}
}