衍生類別建構子前,依階層順序執行所有基底類別建構子(隱式呼叫)。
ColorPoint clrpt = new ColorPoint();
Point pt = clrpt; // 隱式向上轉型
基底參考 pt 持有衍生物件參考,但無法存取衍生專有成員。
衍生類別用 new 隱藏基底同名方法時,仍可用 base 呼叫原版:
public class Point
{
public void invert() { /* 交換 x, y */ }
}
public class ColorPoint : Point
{
public new void invert()
{
int holding = X; X = Y; Y = holding;
screenColor = Color.Gray;
}
public void baseInvert() => base.invert(); // 呼叫基底版本
}
ColorPoint clrpt = new ColorPoint();
clrpt.baseInvert(); // 呼叫基底 invert()
// 或透過基底參考
Point pt = clrpt;
pt.invert(); // 同樣呼叫基底版本
基底類別有多個建構子時,衍生類用 base(參數) 指定呼叫哪個。