C# 繼承類的物件建立


一個類可以派生自多個類或介面,這意味著它可以從多個基類或介面繼承資料和函式。

派生類繼承基類成員變數和成員方法。因此,必須在建立子類之前建立超類物件。你可以在成員初始化列表中為超類初始化提供指令。

下面你可以看到為繼承的類建立的物件。

示例

 演示

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

更新於: 2020-06-23

1000+ 檢視次數

開啟你的 職業生涯

完成課程獲取認證

開始
廣告
© . All rights reserved.