基底類別有多個建構子時,衍生類可用 base 指定呼叫哪一個(Java 用 super):
public class Point
{
private int x, y;
public Point() { x = 0; y = 0; }
public Point(int x, int y) { this.x = x; this.y = y; }
}
public class ColorPoint : Point
{
private Color color;
public ColorPoint(int x, int y) : base(x, y) { color = Color.Red; }
}
關鍵差異:Java 方法預設 virtual,C# 必須明確標記 virtual 才能被覆寫。
virtual 修飾符override 修飾符
using System;
public class CountClass
{
public int count;
public CountClass(int startValue) => count = startValue;
public virtual int StepUp() => ++count;
}
class Count100Class : CountClass
{
public Count100Class(int x) : base(x) { }
public override int StepUp() => base.count + 100;
public static void Main()
{
CountClass counter = new CountClass(10);
CountClass bigCounter = new Count100Class(10);
Console.WriteLine("Value of count in base class = {0}", counter.StepUp());
Console.WriteLine("Value of count in derived class = {0}", bigCounter.StepUp());
}
}
輸出:
Value of count in base class = 11
Value of count in derived class = 110