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
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP