상속, base, sealed

Fruit·2023년 3월 29일

✨ Hello C#!

목록 보기
27/34
post-thumbnail

🌸 상속: :

파생 클래스 이름 : 기반 클래스 이름

기반 클래스, 부모 클래스

  • 물려주는 클래스

파생 클래스, 자식 클래스

  • 물려받는 클래스
  • 자신만의 고유한 멤버 + 클래스로부터 물려받은 멤버


✔️️ 호출 순서

  • 생성: 기반 클래스 → 파생 클래스
  • 소멸: 파생 클래스 → 기반 클래스
using System;

namespace Inheritance
{
    class Base
    {
        public Base()
        {
            Console.WriteLine("Base()");
        }

        ~Base()
        {
            Console.WriteLine("~Base()");
        }
    }

    class Derived : Base       // Base를 상속 받은 파생 클래스
    {
        public Derived()
        {
            Console.WriteLine("Derived()");
        }

        ~Derived()
        {
            Console.WriteLine("~Derived()");
        }
    }
   
    class MainApp
    {
        static void Main(string[] args)
        {
            Derived derived = new Derived();
        }
    }
}

[실행 결과]
Base()
Derived()
~Derived()
~Base()



🌸 base

  • 기반 클래스를 가리킨다.
  • 기반 클래스의 멤버에 접근할 수 있다.
using System;

namespace Inheritance
{
    class Base
    {
        protected string Name;		// protected: 클래스 내, 파생 클래스에서 사용 가능

        public Base(string Name)
        {
            this.Name = Name;
            Console.WriteLine($"Base(): {this.Name}");
        }
        public void BaseMethod()
        {
            Console.WriteLine($"BaseMethod(): {Name}");
        }
    }

    class Derived : Base       // Base를 상속 받은 파생 클래스
    {
        public Derived(string Name) : base(Name)		// Base(string Name)에 매개변수를 넘겨 호출
        {
            Console.WriteLine($"Derived(): {this.Name}");
        }
        public void DerivedMethod()
        {
            base.BaseMethod();		// 기반 클래스에 속한 메소드에 접근
            Console.WriteLine($"DerivedMethod(): {Name}");
        }
    }

    class MainApp
    {
        static void Main(string[] args)
        {
            Base a = new Base("a");
            a.BaseMethod();
            Console.WriteLine();

            Derived b = new Derived("b");
            b.BaseMethod();				// 기반 클래스 메소드 사용
            Console.WriteLine();

            b.DerivedMethod();			// 본인 클래스 메소드 사용
        }
    }
}

[실행 결과]
Base(): a
BaseMethod(): a

Base(): b
Derived(): b
BaseMethod(): b

BaseMethod(): b
DerivedMethod(): b



🌸 sealed

  • 상속되지 않도록 클래스를 봉인한다.
using System;

namespace Inheritance
{
    sealed class Base       // 봉인 클래스
    {
        public Base()
        {
            Console.WriteLine("Base()");
        }
    }

    class Derived : Base       // 에러 발생
    {
        public Derived()
        {
            Console.WriteLine("Derived()");
        }
    }

    class MainApp
    {
        static void Main(string[] args)
        {
            Derived derived = new Derived();
        }
    }
}

▪ 사진 출처: SBS 공식 홈페이지

profile
🌼인생 참 🌻꽃🌻 같다🌼

0개의 댓글