C# 상속으로 기존 클래스에서 새 클래스 파생, 부모(기반)와 자식(파생) 관계 형성. 이 강력한 객체 지향 프로그래밍(OOP) 기능은 코드 재사용과 논리적 구성 촉진.
기반 클래스가 필드, 속성, 메서드 제공하면 파생 클래스가 상속받아 공유 로직 한곳에 두고 동작 확장/커스터마이즈 가능.
C#에서 상속 선언
C#에서 콜론(:)으로 상속 표시:
class Animal {
// 필드와 메서드
}
// Dog가 Animal 상속
class Dog : Animal {
// Animal 필드/메서드
// Dog 고유 필드/메서드
}
Dog가 Animal 확장, 멤버 접근 가능. 다이어그램으로 관계 표현.
예제: 기본 상속
using System;
namespace Inheritance {
// 기반 클래스
class Animal {
public string name;
public void Display() {
Console.WriteLine("I am an animal");
}
}
// 파생 클래스
class Dog : Animal {
public void GetName() {
Console.WriteLine("My name is " + name);
}
}
class Program {
static void Main(string[] args) {
Dog labrador = new Dog();
labrador.name = "Rohu";
labrador.Display();
labrador.GetName();
Console.ReadLine();
}
}
}
출력
I am an animal
My name is Rohu
Dog가 Animal의 name 필드와 Display() 메서드 상속. 파생 클래스 고유 멤버(GetName()) 추가 가능.
"is-a" 관계
상속은 "is-a" 관계 표현. 한 클래스가 다른 클래스 특수 형태일 때 사용.
Dog is an Animal
Apple is a Fruit
Car is a Vehicle
이 관계로 Dog→Animal, Apple→Fruit, Car→Vehicle 상속 정당화.
상속에서 Protected 멤버
protected 필드/메서드는 자신의 클래스와 파생 클래스에서 접근 가능, 외부 코드엔 숨김.
예제: Protected 메서드 사용
using System;
namespace Inheritance {
class Animal {
protected void Eat() {
Console.WriteLine("I can eat");
}
}
class Dog : Animal {
static void Main(string[] args) {
Dog labrador = new Dog();
labrador.Eat();
Console.ReadLine();
}
}
}
출력
I can eat
Eat()이 protected라 Dog 클래스 호출 가능, 계층 외부 코드 불가.
상속 유형 (Types of Inheritance)
상속은 여러 패턴으로 나타남:
1. 단일 상속 (Single Inheritance)
단일 파생 클래스가 한 기반 클래스 상속.
2. 다단계 상속 (Multilevel Inheritance)
기반→파생→또 다른 파생 연쇄.
3. 계층적 상속 (Hierarchical Inheritance)
여러 파생 클래스 동일 기반 클래스 공유.
4. 다중 상속 (Multiple Inheritance)
C#은 다중 클래스 상속 미지원. 인터페이스로 유사 동작 구현 가능.
5. 혼합 상속 (Hybrid Inheritance)
두 가지 이상 상속 유형 조합(예: 다단계 + 계층적).
메서드 오버라이딩 (Method Overriding)
파생 클래스가 기반 클래스 virtual 메서드와 같은 시그니처로 메서드 선언 시 override로 재정의 가능. 다형적 행동 구현.
using System;
namespace Inheritance {
class Animal {
public virtual void Eat() {
Console.WriteLine("I eat food");
}
}
class Dog : Animal {
public override void Eat() {
Console.WriteLine("I eat dog food");
}
}
class Program {
static void Main(string[] args) {
Dog labrador = new Dog();
labrador.Eat();
}
}
}
출력
I eat dog food
Dog의 Eat()이 Animal 것 오버라이드. virtual 허용, override로 대체 표시.
base 키워드 사용
오버라이딩 메서드에서 기반 클래스 구현 호출 필요 시 base 키워드 사용.
예제: 기본 메서드 호출
using System;
namespace Inheritance {
class Animal {
public virtual void Eat() {
Console.WriteLine("Animals eat food.");
}
}
class Dog : Animal {
public override void Eat() {
base.Eat();
Console.WriteLine("Dogs eat dog food.");
}
}
class Program {
static void Main(string[] args) {
Dog labrador = new Dog();
labrador.Eat();
}
}
}
출력
Animals eat food.
Dogs eat dog food.
base.Eat()가 Animal 구현 먼저 호출 후 파생 로직 수행.
C#에서 상속이 중요한 이유
상속으로 관련 클래스 간 재사용 로직 가능. 예: 둘레 계산 공식 공유하는 기하 도형.
RegularPolygon 기반 클래스에 CalculatePerimeter() 메서드.
Square, Rectangle 파생, Length, Sides 등 고유 속성 추가.
각 파생 클래스 면적 계산 자체 구현, 둘레 로직 재사용.
예시 코드
using System;
namespace Inheritance {
class RegularPolygon {
public void CalculatePerimeter(int length, int sides) {
int result = length * sides;
Console.WriteLine("Perimeter: " + result);
}
}
class Square : RegularPolygon {
public int Length = 200;
public int Sides = 4;
public void CalculateArea() {
int area = Length * Length;
Console.WriteLine("Area of Square: " + area);
}
}
class Rectangle : RegularPolygon {
public int Length = 100;
public int Breadth = 200;
public int Sides = 4;
public void CalculateArea() {
int area = Length * Breadth;
Console.WriteLine("Area of Rectangle: " + area);
}
}
class Program {
static void Main(string[] args) {
Square s1 = new Square();
s1.CalculateArea();
s1.CalculatePerimeter(s1.Length, s1.Sides);
Rectangle t1 = new Rectangle();
t1.CalculateArea();
t1.CalculatePerimeter(t1.Length, t1.Sides);
}
}
}
출력
Area of Square: 40000
Perimeter: 800
Area of Rectangle: 20000
Perimeter: 400