상속을 통해 다른 클래스로 클래스를 정의할 수 있으므로 애플리케이션을 쉽게 만들고 유지 관리할 수 있습니다. 이는 또한 코드 기능을 재사용하고 구현 시간을 단축할 수 있는 기회를 제공합니다.
상속은 기본 클래스와 파생 클래스의 개념을 기반으로 합니다. 클래스는 둘 이상의 클래스 또는 인터페이스에서 파생될 수 있습니다. 즉, 여러 기본 클래스 또는 인터페이스에서 데이터와 기능을 상속할 수 있습니다.
기본 클래스와 파생 클래스의 예를 살펴보겠습니다. 여기서 Shape는 기본 클래스이고 Rectangle은 파생 클래스입니다.
class Rectangle: Shape {
// methods
} 다음은 Inheritance −
에서 기본 클래스와 파생 클래스를 사용하는 방법을 보여주는 예입니다.예
using System;
namespace InheritanceApplication {
class Shape {
public void setWidth(int w) {
width = w;
}
public void setHeight(int h) {
height = h;
}
protected int width;
protected int height;
}
// Derived class
class Rectangle: Shape {
public int getArea() {
return (width * height);
}
}
class RectangleTester {
static void Main(string[] args) {
Rectangle Rect = new Rectangle();
Rect.setWidth(5);
Rect.setHeight(7);
// Print the area of the object.
Console.WriteLine("Total area: {0}", Rect.getArea());
Console.ReadKey();
}
}
} 출력
Total area: 35