C Sharp/Abstract classes
< C Sharp
抽象类介于接口和非抽象类之间。
抽象类可以完全不提供成员的实现:
public abstract class AbstractShape
{
public abstract void Draw(Graphics g);
public abstract double X {get; set;}
public abstract double Y {get; set;}
}
这与接口很像。但区别在于抽象类的派生类不能同时从别的类派生(即禁止多重继承)。
一个抽象类可以定义了全部成员:
public abstract class AbstractShape
{
private double _x;
private double _y;
//
// ... (other members)
//
public void Draw(Graphics g) {g.DrawRectangle(Pens.Black, g_rect);}
public double X {get{return _x;}}
public double Y {get{return _y;}}
}
一个抽象类也可以只定义部分成员:
public abstract class AbstractShape
{
private double _x;
private double _y;
//
// ... (other members)
//
public abstract void Draw(Graphics g);
public double X {get{return _x;}}
public double Y {get{return _y;}}
}
显然,不能用new关键字创建抽象类的实例:
AbstractShape shape = new AbstractShape();
但非抽象类可以:
AbstractShape shape = new Square();
实现方法
编辑可用override关键字实现方法或属性:
public class Rectangle : AbstractShape
{
private double _x;
private double _y;
// ...
public override void Draw(Graphics g)
{
g.DrawRectangle(Pens.Black, g_rect);
}
public override double X {
get { return _x; }
set { _x = value; }
}
public override double Y {
get { return _y; }
set { _y = value; }
}
}
覆盖抽象方法和覆盖虚方法一样,不能改变访问指示符(如不能protected转变为public),不能增加缺失的 get 或 set 抽象属性。