객체 지향 C#

Inheritance in C#

Reuse a base class and specialize it: a Developer is an Employee who also knows a language.

  • 중급
  • 2분 분량
  • 실행 가능한 예제 1개
배울 내용
  • Deriving with : BaseClass
  • virtual and override
  • Calling the base constructor
Employee hierarchy
  • EmployeeName, virtual Describe()
    • Developeroverride: "Ada writes C#"

An is-a relationship

상속(inheritance)을 쓰면 새 클래스(자식 클래스)가 기존 클래스(부모 클래스)의 데이터와 메서드를 모두 물려받은 뒤 동작을 추가하거나 바꿀 수 있습니다. 상속은 "개발자는 직원이다"처럼 "~은 ~이다" 관계를 나타내며, 그 관계가 정말 맞을 때만 써야 합니다.

Employee 클래스는 직원의 이름을 저장하고, virtual로 표시된 Describe() 메서드를 가집니다. 자식 클래스가 이 메서드를 재정의할 수 있다는 뜻입니다. Developer 클래스는 Employee를 상속하고, Employee(name)으로 이름을 부모 클래스에 넘기며, override로 프로그래밍 언어까지 설명하도록 바꿉니다. 결과는 Ada writes C#입니다.

핵심 포인트

  1. class Developer(...) : Employee(name) inherits Name and Describe().
  2. virtual lets a method be replaced; override replaces it.
  3. Use inheritance only when the derived type truly is a kind of the base type.

실행 가능한 C# 예제

C#
코드 실행 →
Program.cs
using System;

class Employee(string name)
{
    public string Name { get; } = name;
    public virtual string Describe() => Name;
}

class Developer(string name, string language) : Employee(name)
{
    public override string Describe() => $"{Name} writes {language}";
}

class Program
{
    static void Main() => Console.WriteLine(new Developer("Ada", "C#").Describe());
}
이 예제의 실행 버튼 만들기 실행 결과
Ada writes C#

디버거로 연습하기

중요한 대입이나 조건에 중단점을 두고 Debug를 눌러 다음 줄로 넘어가기 전에 지역 변수 값을 확인하세요.

챌린지로 연습하기

이 레슨에서 배운 내용으로 실제 문제를 풀어 보세요. 모든 챌린지는 브라우저에서 실행되며 즉시 테스트와 AI 리뷰를 받을 수 있습니다.

모든 챌린지