面向對象的原則:
多組合、少繼承;低耦合,高內聚
繼承多關注於共同性;多態著眼於差異性
多態
通過繼承,一個類可以用作多種類型:可以用作它自己的類型、任何基類型,或者在實現接口時用作任何接口類型。這稱為多態性。C# 中的每種類型都是多態的。類型可用作它們自己的類型或用作 Object 實例,因為任何類型都自動將 Object 當作基類型。
1 public class animal
2 {
3
4 public string SayName()
5 {
6 return "hello im animal";
7
8 }
9 public string Eat()
10 {
11
12 return "this is animal's eat";
13 }
14 public virtual string Call()
15 {
16
17 return "this is animal's speak";
18 }
19 }
20 public class Bird:animal
21 {
22 public new string Eat()// 使用新的派生成員替換基成員
23 {
24 return "this is bird's Eat";
25 }
26 public override string Call() //重寫虛方法
27 {
28 return "this is Bird's Call";
29 }
30
31 }
1 /*繼承基類的 eat 和 call 功能*/ 2 /* 3 * result: 4 hello im animal 5 this is bird's Eat 6 this is Bird's Call 7 */ 8 Bird bb = new Bird(); 9 Response.Write(bb.SayName() + "</br>"); 10 Response.Write(bb.Eat()+"</br>"); 11 Response.Write(bb.Call() + "</br>"); 12 13 /* 14 *result: 15 hello im animal 16 this is animal's eat 17 this is Bird's Call 18 */ 19 animal ab = new Bird(); 20 Response.Write(ab.SayName() + "</br>"); 21 Response.Write(ab.Eat() + "</br>"); 22 Response.Write(ab.Call() + "</br>");
new 修飾符:在用作修飾符時,new 關鍵字可以顯式隱藏從基類繼承的成員。
當派生類重寫某個虛擬成員時,即使該派生類的實例被當作基類的實例訪問,也會調用該成員。
封裝
封裝第一原則:將字段定義為private