คลาสสามารถได้รับมาจากคลาสหรืออินเตอร์เฟสมากกว่าหนึ่งคลาส ซึ่งหมายความว่าคลาสสามารถสืบทอดข้อมูลและฟังก์ชันจากคลาสหรืออินเตอร์เฟสพื้นฐานได้หลายคลาส
คลาสที่ได้รับสืบทอดตัวแปรสมาชิกคลาสฐานและวิธีการของสมาชิก ดังนั้น ควรสร้างวัตถุ super class ก่อนสร้าง subclass คุณสามารถให้คำแนะนำสำหรับการเริ่มต้น superclass ได้ในรายการเริ่มต้นสมาชิก
ที่นี่คุณสามารถเห็นวัตถุถูกสร้างขึ้นสำหรับคลาสที่สืบทอดมา
ตัวอย่าง
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