C# - protected

  1. 只有該 class 的區塊才能存取 private 的資源,就算是衍生的類別也算是外部
1
2
3
4
5
6
7
8
9
10
//base class
class Monster
{
private int hp = 100;

public int getHp()
{
return hp;
}
}

protected 關鍵字

用來控管不想讓外部隨意使用,但又想讓繼承的 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
  private void button1_Click(object sender, EventArgs e)
{
Monster mon = new Monster();
Slim slim = new Slim();
MessageBox.Show(""+slim.say());
}

//base class
class Monster
{
//private int hp = 100;
protected int hp = 100;
public int getHp()
{
return hp;
}
protected string introduceSelf()
{
return "I am monster";
}
}
//derivated class
class Slim:Monster
{

public Slim()
{
hp = 500;
}
public string say()
{
return "I am slim";
}
public string say()
{
return introduceSelf()+"I am slim";
}
}

開放程度

public > protected > private

Powered by Hexo and Hexo-theme-hiker

Copyright © 2013 - 2020 CYC'S BLOG All Rights Reserved.

UV : | PV :