본문 바로가기

CS/C#

[ C# ] 상속, 인터페이스, 추상 클래스

1. 상속

상속

= 기존 클래스(부모 클래스)의 속성과 메서드를 재사용하고 확장할 수 있는 기능

= " : " 키워드를 사용하여 상속 구현

= " base " 키워드를 통해 부모 클래스에 접근

 

다이아몬드 문제

= 다중 상속 시, 동일한 조상을 가지는 클래스가 중복되는 경우 발생하는 모호성 문제

= C#은 클래스의 다중 상속을 지원하지 않음

= 인터페이스를 통해 해결 가능

public class Parent
{
    public void Show() => Console.WriteLine("Parent method");
}

public class Child : Parent
{
    public void Display() => Console.WriteLine("Child method");
}

// 사용 예시
Child child = new Child();
child.Show(); // Parent의 메서드
child.Display(); // Child의 메서드

 

2. 인터페이스

계약

= 인터페이스는 클래스 설계를 더 유연하게 만들고, 쉽게 확장할 수 있도록 만들어줌

= 클래스는 인터페이스에 정의된 모든 메서드를 구현해야함

 

추상화

= 메서드 시그니처만 정의

= 메서드 구현은 해당 인터페이스를 구현하는 클래스가 수행

public interface IWalkable
{
    void Walk();
}

public interface IRunnable
{
    void Run();
}

public class Animal : IWalkable, IRunnable
{
    public void Walk() => Console.WriteLine("Walking...");
    public void Run() => Console.WriteLine("Running...");
}

// 사용 예시
Animal animal = new Animal();
animal.Walk(); // Walking...
animal.Run(); // Running...

 

다중 상속

= 인터페이스 다중 상속 가능

= 명시적 인터페이스 구현을 통해 동일한 메서드 이름을 가진 경우 모호성 해결 가능

using System;

public interface IWalkable
{
    void Move();
}

public interface IFlyable
{
    void Move();
}

public class Animal : IWalkable, IFlyable
{
    // 명시적 인터페이스 구현으로 Move() 메서드를 각각 정의
    void IWalkable.Move() => Console.WriteLine("Animal is walking.");
    void IFlyable.Move() => Console.WriteLine("Animal is flying.");
}

public class Program
{
    public static void Main()
    {
        Animal animal = new Animal();
        
        // 인터페이스를 명시적으로 캐스팅하여 호출
        ((IWalkable)animal).Move(); // "Animal is walking."
        ((IFlyable)animal).Move();   // "Animal is flying."
    }
}

 

3. 추상 클래스

인터페이스

= 다중 상속 가능

= 특정 행위를 규정하고 계약을 정의하는데 사용

 

추상 클래스

= 단일 상속만 가능

= 공통된 기본 구현을 제공하하고, 자식 클래스에 따라 재정의될 수 있는 메서드 포함

public abstract class Shape
{
    public abstract double GetArea(); // 추상 메서드

    public void Display() => Console.WriteLine("Displaying shape...");
}

public class Circle : Shape
{
    private double radius;

    public Circle(double radius) => this.radius = radius;

    public override double GetArea() => Math.PI * radius * radius; // 재정의
}

// 사용 예시
Circle circle = new Circle(5);
circle.Display(); // Displaying shape...
Console.WriteLine($"Area: {circle.GetArea()}"); // Area: 78.54

'CS > C#' 카테고리의 다른 글

[ C# ] 값 형식, 참조 형식  (0) 2024.09.26
[ C# ] Callback, Delegate, Event  (0) 2024.08.09
[ C# ] 객체지향 프로그래밍  (0) 2024.07.26
[ C# ] 객체와 한정자  (0) 2024.07.26