클래스를 생성할 때 완전히 새로운 데이터 멤버와 멤버 함수를 작성하는 대신 프로그래머는 새 클래스가 기존 클래스의 멤버를 상속하도록 지정할 수 있습니다. 이 기존 클래스를 기본 클래스라고 하고 새 클래스를 파생 클래스라고 합니다.
클래스는 둘 이상의 클래스 또는 인터페이스에서 파생될 수 있습니다. 즉, 여러 기본 클래스 또는 인터페이스에서 데이터와 기능을 상속할 수 있습니다.
다음은 C#의 기본 클래스 구문입니다. −
<access-specifier> class <base_class> {
...
}
class <derived_class> : <base_class> {
...
} 예를 들어 보겠습니다 -
예시
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();
}
}
}