클래스는 둘 이상의 클래스 또는 인터페이스에서 파생될 수 있습니다. 즉, 여러 기본 클래스 또는 인터페이스에서 데이터와 기능을 상속할 수 있습니다.
파생 클래스는 기본 클래스 멤버 변수와 멤버 메서드를 상속합니다. 따라서 상위 클래스 객체는 하위 클래스가 생성되기 전에 생성되어야 합니다. 멤버 초기화 목록에서 슈퍼클래스 초기화에 대한 지침을 제공할 수 있습니다.
여기에서 상속받은 클래스에 대해 생성된 객체를 볼 수 있습니다.
예
using System;
namespace Demo {
class Rectangle {
protected double length;
protected double width;
public Rectangle(double l, double w) {
length = l;
width = w;
}
public double GetArea() {
return length * width;
}
public void Display() {
Console.WriteLine("Length: {0}", length);
Console.WriteLine("Width: {0}", width);
Console.WriteLine("Area: {0}", GetArea());
}
}
class Tabletop : Rectangle {
private double cost;
public Tabletop(double l, double w) : base(l, w) { }
public double GetCost() {
double cost;
cost = GetArea() * 70;
return cost;
}
public void Display() {
base.Display();
Console.WriteLine("Cost: {0}", GetCost());
}
}
class ExecuteRectangle {
static void Main(string[] args) {
Tabletop t = new Tabletop(3, 8);
t.Display();
Console.ReadLine();
}
}
} 출력
Length: 3 Width: 8 Area: 24 Cost: 1680