# 什麼是物件導向?
物件導向是一種程式設計的方法,重點是把資料與行為包裝成物件。
C#
// 類別
public class Animal {
public string Name { get; set; }
public int Age { get; set; }
public string Sound { get; set; }
public void Bark() {
Console.WriteLine(Sound);
}
}
// 物件
var cat = new Animal { Name = "kitty", Age = 1, Sound = "meow" };
cat.Bark(); // 輸出:meow
# 三大特性?
# 封裝(Encapsulation)
把資料和邏輯包起來,只開放必要的方法,避免外部直接修改。
C#
class BankAccount
{
private decimal balance; // 餘額
public BankAccount(decimal initialBalance)
{
balance = initialBalance;
}
public decimal Balance => balance; // 只允許查看餘額
// 存
public void Deposit(decimal amount)
{
if(amount <= 0)
throw new ArgumentException("金額必須大於 0");
balance += amount;
}
// 提
public void Withdraw(decimal amount)
{
if(amount <= 0)
throw new ArgumentException("金額必須大於 0");
if(amount > balance)
throw new InvalidOperationException("餘額不足");
balance -= amount;
}
}
// 使用範例
var account = new BankAccount(1000);
account.Deposit(200); // 存入 200
account.Withdraw(500); // 提取 500
Console.WriteLine(account.Balance); // print: 700
# 繼承(Inheritance)
子類別可以共用父類別的屬性和方法,減少重複程式碼。
C#
public class Cat : Animal
{
public double Weight { get; set; }
}
// 使用範例
var kitty = new Cat { Name = "kitty", Age = 1, Sound = "meow", Weight = 4.2 };
kitty.Bark(); // print: meow
# 多型(Polymorphism)
相同方法名稱可以在不同類別中表現不同行為。
使用關鍵字:virtual(可被覆寫)、override(覆寫父類別行為)。
C#
public class Animal
{
public virtual void MakeSound()
{
Console.WriteLine("make some noise");
}
}
public class Cat : Animal
{
public override void MakeSound()
{
Console.WriteLine("meow meow");
}
}
// 使用範例
Animal cat = new Cat();
cat.MakeSound(); // print: meow meow
# 最後的想法
物件導向最大的目的是讓程式更容易維護、擴充與理解。
透過封裝、繼承與多型,可以更有結構地設計程式,讓邏輯更清晰、可重用性更高。
不過,在實務開發中也要拿捏平衡。
若過度拆分類別、為了「物件導向」而「過度設計」,
反而會讓系統變得複雜、難以維護。