一个类可以从一个以上的类或接口派生,这意味着它可以从多个基类或接口继承数据和函数。
派生类继承基类的成员变量和成员方法。因此,应在创建子类之前创建超类对象。您可以在成员初始化列表中提供有关超类初始化的说明。
在这里,您可以看到为继承的类创建了对象。
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