C#

Nested Inheritance, base, sealed

binary는 호남선 2024. 11. 10. 20:17

Nested Inheritance (중첩 상속)

- 이미 다른 클래스로부터 상속 받은 클래스가 다른 클래스를 상속

- 다중 상속과는 다른 개념

class Player
{
    public virtual void Move()
    {
        Console.WriteLine("Player Move!");
    }
}
class Knight : Player
{
    public override void Move()
    {
        Console.WriteLine("Knight Move!");
    }
}
class SuperKnight : Knight
{
    public override void Move()
    {
        Console.WriteLine("SuperKnight Move!");
    }
}
class Program
{
    static void EnterGame(Player player)
    {
        player.Move();
    }
    static void Main(string[] args)
    {
        Knight knight = new Knight();
        SuperKnight superknight = new SuperKnight();

        knight.Move();
        superknight.Move();

        // Knight Move!
        // SuperKnight Move!
    }
}

base & sealed

- base : 기존 함수의 내용을 그대로 유지하면서 기능을 추가할 때 사용

- sealed : 상속 받은 함수를 자신의 클래스까지만 사용하고 자신의 자식 클래스에게 상속 x

class Player
{
    public virtual void Move()
    {
        Console.WriteLine("Player Move!");
    }
}
class Knight : Player
{
    public sealed override void Move()
    {
        base.Move();
        // player.Move()를 한번 호출
        Console.WriteLine("Knight Move!");
    }
}
class SuperKnight : Knight
{
    // Error!
    // 부모 클래스에서 함수가 봉인되어 재정의 불가
    // public override void Move()
    // {
    //    Console.WriteLine("SuperKnight Move!");
    // }
}
class Program
{
    static void Main(string[] args)
    {
        Knight knight = new Knight();
        SuperKnight superknight = new SuperKnight();

        knight.Move();
        // Player Move!
        // Knight Move!
    }
}

 

내용 출처 : Inflearn Rookiss님 강의 [C#과 유니티로 만드는 MMORPG 게임 개발 시리즈] Part1: C# 기초 프로그래밍 입문

https://www.inflearn.com/course/%EC%9C%A0%EB%8B%88%ED%8B%B0-mmorpg-%EA%B0%9C%EB%B0%9C-part1