인터페이스의 특징은 선언부에 메서드 구현을 포함하지 않는다는 것이다. 단지 메서드의 이름, 매개변수, 반환값의 형식 등을 정의한다.
예시1:
// interfaceinterfaceIAnimal
{
voidanimalSound(); // interface method (does not have a body)voidrun(); // interface method (does not have a body)
}
// 코드 출처 : w3schools
인터페이스의 이름은 시작 부분에 문자 ‘I’로 시작하는 것이 일반적이다. 클래스와 인터페이스를 구분하기 위함이다.
인터페이스 사용 방법
인터페이스를 구현하는 방법은 클래스가 클래스를 상속할 때와 같이 ‘:’ 기호를 사용한다.
예시2:
// 인터페이스interfaceIAnimal
{
voidanimalSound(); // 인터페이스 메서드
}
// Pig "implements" the IAnimal interfaceclassPig : IAnimal
{
publicvoidanimalSound()
{
// The body of animalSound() is provided here
Console.WriteLine("The pig says: wee wee");
}
}
classProgram
{
staticvoidMain(string[] args)
{
Pig myPig = new Pig(); // Create a Pig object
myPig.animalSound();
}
}
// 코드 출처 : w3schools
인터페이스의 특징
인터페이스에 정의해 놓은 메서드는 구현부에서 반드시 재정의 해야 한다. 예시2에서는 IAnimal 인터페이스에 animalSound 메서드가 정의되었다.
이를 Pig 클래스에서 구현할 때 animalSound 메서드를 재정의해주었다. 추상화는 추상 클래스 내에 정의된 메서드 외에도 이를 상속받은 클래스에서 새로운 메서드나 변수 등을 선언할 수 있었지만, 인터페이스는 불가능하다.
인터페이스는 기존에 정의된 속성과 메서드 외에는 추가할 수 없다.
예시3:
// 추상화(Abstraction) 예제// 추상 클래스인 AnimalabstractclassAnimal
{
// 추상 메서드 MakeSound 정의publicabstractvoidMakeSound();
}
// Animal을 상속받은 Dog 클래스 (살)classDog : Animal
{
// MakeSound 메서드 구현publicoverridevoidMakeSound()
{
Console.WriteLine("멍멍!");
}
// Dog 클래스의 특정한 기능과 속성publicvoidWagTail()
{
Console.WriteLine("꼬리를 흔들며 행복해요!");
}
}
// Animal을 상속받은 Cat 클래스 (장기)classCat : Animal
{
// MakeSound 메서드 구현publicoverridevoidMakeSound()
{
Console.WriteLine("야옹!");
}
// Cat 클래스의 특정한 기능과 속성publicvoidPurr()
{
Console.WriteLine("산소온거니까 편안해요.");
}
}
// 인터페이스(Interface) 예제interfaceIShape
{
voidDraw();
}
classRectangle : IShape
{
publicvoidDraw()
{
Console.WriteLine("사각형을 그립니다.");
}
}
classCircle : IShape
{
publicvoidDraw()
{
Console.WriteLine("원을 그립니다.");
}
}
classProgram
{
staticvoidMain(string[] args)
{
// 추상화 예제
Animal dog = new Dog();
dog.MakeSound(); // "멍멍!" 출력
dog.WagTail();
Animal cat = new Cat();
cat.MakeSound(); // "야옹~" 출력
cat.Purr();
// 인터페이스 예제
IShape rectangle = new Rectangle();
rectangle.Draw(); // "사각형을 그립니다." 출력
IShape circle = new Circle();
circle.Draw(); // "원을 그립니다." 출력
}
}
또한 인터페이스는 여러 개를 한 번에 구현할 수 있다. 예시4를 살펴보자. IFirstInterface와 ISecondInterface를 선언했고, DemoClass는 이 두 인터페이스를 모두 구현했다. 이를 다중 인터페이스라고 한다. 구현은 ,기호로 구분하여한다.