๋ณธ๋ฌธ์œผ๋กœ ๋ฐ”๋กœ๊ฐ€๊ธฐ
728x90

 

 

 

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);
     }    // ๋ถ€๋ชจ ์ƒ์„ฑ์ž๊ฐ€ ์ž˜ ํ˜ธ์ถœ๋˜์—ˆ๋Š”์ง€ ์•Œ์•„๋ณด๊ธฐ ์œ„ํ•ด ๋ชฌ์Šคํ„ฐ ์ด๋ฆ„ ์ถœ๋ ฅ
}

 

 

์›ํ•˜๋Š” ๋ถ€๋ชจ ํด๋ž˜์Šค์˜ ์ƒ์„ฑ์ž๋ฅผ ๊ณจ๋ผ์„œ ํ˜ธ์ถœํ•˜๋Š” ๋ชจ์Šต์„ ๋ณผ ์ˆ˜ ์žˆ์—ˆ๋‹ค.

 

 

728x90
๋ฐ˜์‘ํ˜•