學習重點:
- 繼承性的好處 - 減少程式碼的重複性(包含class內部),讓程式碼易於維護
主程式 :
private void button1_Click(object sender, EventArgs e)
{
Village vi1 = new Village();
Monster mon1 = new Monster();
Monster mon2 = new Monster();
mon1.Attack(vi1);
mon1.Attack(mon2);
mon1.Attack(mon2);
MessageBox.Show("怪物1 HP:" + mon1.GetHP() + "\n" +
"怪物2 HP:" + mon2.GetHP() + "\n" +
"村民1 HP:" + vi1.GetHP() + "\n");
}
Creature 類別 :
class Creature // 基底類別/父類別 (Base Class)
{
private int hp = 100;
public int GetHP()
{
return hp;
}
public void Injured(int injuredPoint)
{
hp -= injuredPoint;
}
}
Monster 類別 :
class Monster : Creature // 衍生類別/子類別(Derived Class) 繼承Creature的屬性與方法
{
public void Attack(Creature c) // 不用重複寫多個不同的Attack(XXX)方法
{
c.Injured(10);
}
}
Village 類別 :
class Village : Creature // 衍生類別/子類別(Derived Class) 繼承Creature的屬性與方法
{
public string Talk()
{
return "呵呵";
}
}
執行結果:
沒有留言:
張貼留言