base ํค์๋๋?
์์ ํด๋์ค์์ ๋ถ๋ชจ ํด๋์ค์ ๋ฉค๋ฒ์ ์ ๊ทผํ ๋ ์ฌ์ฉํ๋ค. ์ด๋ฐ ์ํฉ์ด ์์ ์ ์๋ค.
"๋ถ๋ชจ ํด๋์ค์ ์์ ํด๋์ค ๋ชจ๋ ๋์ผํ ์ด๋ฆ์ ๋ณ์๊ฐ ์๋ค๋ฉด?"
์ด ๊ฒฝ์ฐ์๋ ๋ถ๋ชจ ํด๋์ค์ ๋ณ์์ ์์ ํด๋์ค์ ๋ณ์๋ฅผ ๊ตฌ๋ถํด์ค ์๋ณ์๊ฐ ํ์ํ๋ค. ์ด ๋, base ํค์๋๊ฐ ์ฌ์ฉ๋๋ค.
class Monster
{
protected string name;
protected int hp;
protected int attackDamage = 1;
}
class Slime : Monster
{
protected int attackDamage;
public Slime()
{
this.attackDamage = 5;
Console.WriteLine("์์ ํด๋์ค์ attackPower = {0}", this.attackDamage);
Console.WriteLine("๋ถ๋ชจ ํด๋์ค์ attackPower = {0}", base.attackDamage);
}
}
์ฆ, ์์ ๊ฐ์ด base ํค์๋๋ฅผ ํตํด ๋ถ๋ชจ ํด๋์ค์ ๋ฉค๋ฒ์ ์ ๊ทผํ ์ ์๋ค.
์ฐธ๊ณ ๋ก, base์ this ํค์๋๋ฅผ ์ฌ์ฉํ์ง ์๊ณ ์ด๋ฆ์ด ๊ฒน์น๋ ๋ฉค๋ฒ๋ฅผ ํธ์ถํ๋ค๋ฉด this๊ฐ ์ฐ์ ๊ถ์ ๊ฐ๋๋ค.
base() ์์ฑ์๋?
this() ์์ฑ์๋ฅผ ํตํด ํด๋์ค ๋ด์ ์๋ ๋ค๋ฅธ ์์ฑ์๋ฅผ ํธ์ถํ ์ ์์๋ค. ๋น์ทํ ๊ฐ๋ ์ผ๋ก, base() ์์ฑ์๋ฅผ ํตํด ์์ ํด๋์ค์์ ๋ถ๋ชจ ํด๋์ค ๋ด๋ถ์ ์์ฑ์๋ฅผ ๋ช ์์ ์ผ๋ก ํธ์ถํ ์ ์๋ค.
class Monster
{
protected string name;
protected int hp;
protected int attackPower = 10;
public Monster(string name) // ์ด๋ฆ์ ๋งค๊ฐ ๋ณ์๋ก ๋ฐ๋ ์์ฑ์
{
this.name = name;
}
public Monster(string name, int hp) // ์ด๋ฆ๊ณผ hp๋ฅผ ๋งค๊ฐ ๋ณ์๋ก ๋ฐ๋ ์์ฑ์
{
this.name = name;
this.hp = hp;
}
}
class Slime : Monster
{
public Slime() : base("์ฌ๋ผ์") // Monster(string name) ์์ฑ์ ํธ์ถ
{
Console.WriteLine("๋ชฌ์คํฐ ์ด๋ฆ : {0}", name);
} // ๋ถ๋ชจ ์์ฑ์๊ฐ ์ ํธ์ถ๋์๋์ง ์์๋ณด๊ธฐ ์ํด ๋ชฌ์คํฐ ์ด๋ฆ ์ถ๋ ฅ
}
์ํ๋ ๋ถ๋ชจ ํด๋์ค์ ์์ฑ์๋ฅผ ๊ณจ๋ผ์ ํธ์ถํ๋ ๋ชจ์ต์ ๋ณผ ์ ์์๋ค.