C# 继承类的对象创建

csharpprogrammingserver side programming更新于 2024/9/12 7:34:00

一个类可以从多个类或接口派生,这意味着它可以从多个基类或接口继承数据和函数。

派生类继承了基类的成员变量和成员方法。因此,在创建子类之前应该先创建超类对象。您可以在成员初始化列表中给出超类初始化的说明。

在这里您可以看到为继承类创建的对象。

示例

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

相关文章