인터페이스

강성현
∙∙조회 6

인터페이스(interface)란?

특정 동작들을 공통적으로 가지고 있는 것들을 분류하기 위한 용도로 사용됩니다.

또한, 해당 인터페이스를 무조건 구현해야하므로 까먹고 기능을 구현하지 않는 실수도 예방할 수 있습니다.

 

문법형식 :

public interface I<이름>

{

<반환형> <메서드 이름> (<매개변수>);

}

  • 인터페이스는 ==다중 구현이 가능==하다.

 

csharp

// 데미지를 받을 수 있는 애들
IDamageable[] damageables = new IDamageable[]
{
     new Slime(),
     new NPC()
};

추상클래스와 인터페이스의 차이

항목추상 클래스인터페이스
필드가질 수 있음가질 수 없음
생성자가질 수 있음가질 수 없음
구현된 메서드가질 수 있음이 과정에서는 다루지 않음
접근 제한자지정 가능지정하지 않음. 자동으로 공개
몇 개를 붙일 수 있는가하나여러 개
관계"~이다""~할 수 있다"

 

csharp
using System;

public class Program
{
    public static void Main(string[] args)
    {
        Guardian g = new();
        Slime s = new();
        
        Monster[] monsters = new Monster[]
        {
            g,
            s
        };

        foreach (Monster monster in monsters)
        {
            if (monster is IDamageable)
            {
                IDamageable damageable = monster as IDamageable;
                damageable.TakeDamage(10);
            }
        }

        Console.WriteLine(g.Health);
        Console.WriteLine(s.Health);
    }
}

public interface IDamageable
{
    public void TakeDamage(int damage);
}

public class Guardian : Monster
{
    public void TakeDamage(int damage)
    {
        Health -= damage;
        Console.WriteLine($"가디언 데미지 입음 : Health : {Health}");
    }
}

public class Slime : Monster, IDamageable
{
    public void TakeDamage(int damage)
    {
        Health -= damage;
        Console.WriteLine($"슬라임 데미지 입음. Health : {Health}");
    }
}

public abstract class Monster
{
    public int Health { get; protected set; } = 100;
}