18. class Program
{
static void Main()
{
//SavingsAccount建立之帳戶
SavingsAccount savingsAccount = new SavingsAccount("S-0001", 0, 2.5m);
savingsAccount.Deposit(500);
savingsAccount.Withdraw(200);
Console.WriteLine();
//AccountBase建立之帳戶
AccountBase account = new AccountBase("A-0001", 0);
account.Deposit(5000);
account.Withdraw(3000);
Console.Read();
}
}
多型範例2-3
(base / this)
18
19. abstract class Shape //抽象類別
{
public abstract int GetArea(); //抽象方法
}
class Square : Shape
{
private int _side;
public Square(int n) => _side = n;
public override int GetArea() => _side * _side; //子類別必須override 抽象方法
}
//--------------------------------------------------------------------------------------
class Program {
static void Main()
{
Square sq = new Square(13);
Console.WriteLine($"Area of the square = {sq.GetArea()}"); // Area of the square = 169
}}
//--------------------------------------------------------------------------------------
Shape shape = new Shape();
抽象類別 (Abstract Class)
使用 abstract表示,該Class只是作為其他Class的基底,不自行實體化
19
41. 依賴反轉原則 (Dependency inversion principle)
★ 高層模組不應該依賴低層模組,兩者都應該依賴抽象介面
High-level modules should not import anything from low-level modules.
Both should depend on abstractions (e.g., interfaces).
★ 抽象介面不應該依賴具體實現,具體實現應該依賴抽象介面
Abstractions should not depend on details.
Details (concrete implementations) should depend on abstractions.
★ 「應依賴於抽象而不是一個實體」
41