OOP

介紹 OOP 三大特性和 abstract, virtual, interface, generic 概念

Encapsulation 封裝

  1. 使用者不需要知道背後的實作內容,只需要知道 method 提供的介面怎麼使用就好
  2. 像是一個 class 可能有 private method,自己內部去操作,別人不會知道這個 method

Inheritance 繼承

假如現在有一個 class Cat

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
class Cat
{
	private string name = "";
	public Cat(string name) {
		this.name = name;
	}
	
	public string Shout() {
			return "我的名字叫做"+name+"喵";
	}
}

如果你想新增另一個 class Dog,功能和 Cat 差不多,你可以選擇去複製一模一樣的程式碼,只是 code 就重複了,不是好的寫法。 因此可以宣告一個 Animal 的 parent class,並把原本 private 改成 protected,讓 Cat & Dog 都去繼承這個 parent class。

  • private: 只有該 class 可以 access
  • protected: 只有該 class 跟他的 child class 可以 access
  • public: 任何人都可以 access

Polymorphism 多型

  • 多載(Overloading): 根據參數的個數和類型來決定使用哪一個方法
  • 複寫(Overriding): parent class 建立一個 virtual method,讓 children class override

Abstract class vs. Interface:

  • Abstract: 定義存在的東西、角色 (不可以被 new 出來的 class)
  • Interface: 定義行為
  • 舉例:看似不相關的東西,例如鳥跟竹蜻蜓,可能就不適合用 abstract,因為他們沒有共通的 property,一個是物品,一個是動物,但可以用 interface,因為共同行為是 fly

Abstract method vs. Virtual method:

  • abstract: 代表是抽象的,不會去寫一些共同的行為
    • 會希望一定要去 override 他,在 compile time 中如果沒有去 override 可能就會報錯。
  • virtual: 可以寫一些共同行為,其他人看要不要 override
    • 沒有 override 不會報錯,因為 virtual 可以定義共同的行為。

Generic

可以使用 Template 的方式在定義 method 或是 class 時不先宣告特定 type,而是用 T 代替。如此即能夠非常彈性地設計一個能夠接受不同 type 的 class。使用 Generic 可以將 class 定義成下面的樣子:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
public class GenericList<T>
{
	public void Add(T val)
	{
		// Add implementation
	}
	// other methods...
}

// 接著就可以透過 Generic 接收不同 type 並實作 List

var numbers = new GenericList<int>();
numbers.Add(5) // 這時 compiler 就會自動提示說要 input int value

var books = new GenericList<Book>();
books.Add(new Book());
comments powered by Disqus