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 抽象屬性。