상속을 통해 다른 클래스의 관점에서 클래스를 정의할 수 있으므로 애플리케이션을 더 쉽게 만들고 유지 관리할 수 있습니다.
클래스를 생성할 때 완전히 새로운 데이터 멤버와 멤버 함수를 작성하는 대신 프로그래머는 새 클래스가 기존 클래스의 멤버를 상속하도록 지정할 수 있습니다. 이 기존 클래스를 기본 클래스라고 하고 새 클래스를 파생 클래스라고 합니다. 클래스는 둘 이상의 클래스 또는 인터페이스에서 파생될 수 있습니다. 즉, 여러 기본 클래스 또는 인터페이스에서 데이터와 기능을 상속할 수 있습니다.피>
예를 들어 보겠습니다 -
예
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 Demo {
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