什麼是C#中的基類?
在建立類時,程式設計師可以指定新類應繼承現有類的成員,而不是編寫全新的資料成員和成員函式。 此現有的類稱為基類,而新類稱為派生類。
一個類可以從多個類或介面派生,這意味著它可以從多個基類或介面繼承資料和函式。
以下是 C# 中基類的語法 −
<access-specifier> class <base_class> { ... } class <derived_class> : <base_class> { ... }
讓我們來看一個示例 −
示例
using System; namespace InheritanceApplication { class Shape { public void setWidth(int w) { width = w; } public void setHeight(int h) { height = h; } protected int width; protected int height; } // Derived class class Rectangle: Shape { public int getArea() { return (width * height); } } class RectangleTester { static void Main(string[] args) { Rectangle Rect = new Rectangle(); Rect.setWidth(5); Rect.setHeight(7); // Print the area of the object. Console.WriteLine("Total area: {0}", Rect.getArea()); Console.ReadKey(); } } }
廣告