인터페이스
본문 로딩 중...
댓글 0
댓글을 작성하려면 로그인이 필요합니다.
아직 댓글이 없습니다. 첫 번째 댓글을 작성해보세요.
특정 동작들을 공통적으로 가지고 있는 것들을 분류하기 위한 용도로 사용됩니다.
또한, 해당 인터페이스를 무조건 구현해야하므로 까먹고 기능을 구현하지 않는 실수도 예방할 수 있습니다.
문법형식 :
public interface I<이름>
{
<반환형> <메서드 이름> (<매개변수>);
}
// 데미지를 받을 수 있는 애들
IDamageable[] damageables = new IDamageable[]
{
new Slime(),
new NPC()
};
| 항목 | 추상 클래스 | 인터페이스 |
|---|---|---|
| 필드 | 가질 수 있음 | 가질 수 없음 |
| 생성자 | 가질 수 있음 | 가질 수 없음 |
| 구현된 메서드 | 가질 수 있음 | 이 과정에서는 다루지 않음 |
| 접근 제한자 | 지정 가능 | 지정하지 않음. 자동으로 공개 |
| 몇 개를 붙일 수 있는가 | 하나 | 여러 개 |
| 관계 | "~이다" | "~할 수 있다" |
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;
}