본문 바로가기
Programming

C# 인터페이스와 추상 클래스

by 나무수피아는 지식의 가지를 뻗어가는 공간입니다. 2025. 12. 6.
반응형

인터페이스 정의 및 구현

   인터페이스는 클래스가 반드시 구현해야 하는 메서드나 속성을 정의하는 계약을 제공합니다. 인터페이스는 메서드 시그니처만 정의하며, 그 구현은 인터페이스를 구현한 클래스에서 제공됩니다.

인터페이스 예시


public interface IAnimal
{
    void Speak();  // 메서드 시그니처만 정의
}

public class Dog : IAnimal
{
    public void Speak()
    {
        Console.WriteLine("Dog barks");
    }
}

public class Cat : IAnimal
{
    public void Speak()
    {
        Console.WriteLine("Cat meows");
    }
}

class Program
{
    static void Main()
    {
        IAnimal animal1 = new Dog();
        IAnimal animal2 = new Cat();

        animal1.Speak();  // Dog barks
        animal2.Speak();  // Cat meows
    }
}

IAnimal 인터페이스는 `Speak` 메서드를 정의하고, 이를 구현한 DogCat 클래스가 각기 다른 방식으로 구현합니다. 인터페이스를 통해 다형성을 적용할 수 있습니다.

추상 클래스와 비교

   추상 클래스는 하나 이상의 추상 메서드를 가질 수 있는 클래스입니다. 추상 클래스는 기본 구현을 제공하거나, 자식 클래스에서 반드시 구현해야 할 메서드를 정의합니다. 반면, 인터페이스는 구현 없이 메서드 시그니처만 제공하는 차이가 있습니다.

추상 클래스 예시


public abstract class Animal
{
    public abstract void Speak();  // 추상 메서드

    public void Sleep()
    {
        Console.WriteLine("Animal is sleeping");
    }
}

public class Dog : Animal
{
    public override void Speak()
    {
        Console.WriteLine("Dog barks");
    }
}

public class Cat : Animal
{
    public override void Speak()
    {
        Console.WriteLine("Cat meows");
    }
}

class Program
{
    static void Main()
    {
        Animal animal1 = new Dog();
        Animal animal2 = new Cat();

        animal1.Speak();  // Dog barks
        animal1.Sleep();  // Animal is sleeping
        animal2.Speak();  // Cat meows
        animal2.Sleep();  // Animal is sleeping
    }
}

추상 클래스인 Animal은 `Speak` 메서드를 추상 메서드로 선언하고, `Sleep` 메서드는 구현된 상태입니다. 이를 상속한 자식 클래스들에서는 `Speak`를 오버라이드해야 합니다.

다형성 활용

   다형성은 인터페이스나 추상 클래스를 사용하여 동일한 메서드를 다른 형태로 구현할 수 있게 합니다. 이를 통해 유연한 코드와 재사용이 가능해집니다. 인터페이스나 추상 클래스를 사용하면 다양한 객체가 공통된 메서드를 가지고 있으므로, 객체의 구체적인 타입에 의존하지 않고 동작할 수 있습니다.

다형성 예시


public interface IShape
{
    void Draw();
}

public class Circle : IShape
{
    public void Draw()
    {
        Console.WriteLine("Drawing Circle");
    }
}

public class Square : IShape
{
    public void Draw()
    {
        Console.WriteLine("Drawing Square");
    }
}

class Program
{
    static void Main()
    {
        IShape shape1 = new Circle();
        IShape shape2 = new Square();

        shape1.Draw();  // Drawing Circle
        shape2.Draw();  // Drawing Square
    }
}

`IShape` 인터페이스를 사용하여 CircleSquare 클래스는 각각 `Draw` 메서드를 구현합니다. 다형성 덕분에 동일한 타입인 `IShape`를 통해 서로 다른 형태의 객체를 다룰 수 있습니다.

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

특징 인터페이스 추상 클래스
메서드 구현 없음 (시그니처만) 가능 (일부는 추상 메서드일 수 있음)
다중 상속 가능 불가능 (하나의 클래스만 상속 가능)
속성 없음 (메서드만 있음) 가능
반응형

'Programming' 카테고리의 다른 글

C# 객체지향 프로그래밍 (OOP)  (0) 2025.12.08
C# 클래스와 객체  (0) 2025.12.07
C# 메서드와 매개변수  (0) 2025.12.05
C# 배열과 컬렉션 기초  (0) 2025.12.04
C# 연산자와 제어문  (6) 2025.12.03