建構函式參數 讓實例化時傳遞初始化資料,支援多載提供不同初始化路徑。
class Vehicle {
public int Wheels; protected float Weight;
public Vehicle() {}
public Vehicle(int w, float g) { Wheels=w; Weight=g; }
public void Show() => Console.WriteLine($"W:{Wheels} Wt:{Weight}");
}
class Train {
public int Num; private int Passengers; private float Weight;
public Train() {}
public Train(int n, int p, float w) { Num=n; Passengers=p; Weight=w; }
public void Show() => Console.WriteLine($"N:{Num} Wt:{Weight} P:{Passengers}");
}
class Car : Vehicle {
int Passengers;
public Car(int w, float g, int p) : base(w,g) { Passengers=p; }
public new void Show() => Console.WriteLine($"W:{Wheels} Wt:{Weight} P:{Passengers}");
}
class Test {
static void Main() {
Vehicle v1 = new Vehicle(4,5);
Train t1 = new Train();
Train t2 = new Train(10,100,100);
Car c1 = new Car(4,2,4);
v1.Show(); t1.Show(); t2.Show(); c1.Show();
}
}
W:4 Wt:5 N:0 Wt:0 P:0 N:10 Wt:100 P:100 W:4 Wt:2 P:4
Car 以 : base(w,g) 明確呼叫基類建構函式。new void Show() 隱藏基類 Show(非覆寫)。