Andy's blog

If you always do what you've always done, you'll always get what you've always got.

0%

2021-02-22-繼承性(續)

今天來認識繼承性


參考資料:
小山的 C# 教學-第29課-繼承性(續)


名詞說明

1
2
3
4
5
6
1. 我們通常把被繼承的 class 稱為基底類別(Base Class) EX:Demo
2. 繼承的 class 稱為衍生類別 (Derived Class) EX:Demo2
public class Demo2: Demo
{
private int hurt;
}

減少相同class 重複程式碼範例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
public class Demo
{
private int hp;
public string getHp()
{
return hp;
}

public void hurt(int point)
{
hp -= point;
}
}
//繼承Demo屬性和方法
public class Demo2: Demo
{
public void Attack(Demo d)
{
d.hurt(10);
}
}

public class Demo3: Demo
{

}


public class Test
{
Demo2 monster1 = new Demo2();
Demo3 monster2 = new Demo3();

monster1.Attack(monster1);
monster2.Attack(monster2);

}