C# 繼承
繼承 (派生類和基類)
在 C# 中,可以從一個類繼承欄位和方法。我們將“繼承概念”分為兩類:
- 派生類 (子類) - 繼承另一個類的類
- 基類 (父類) - 被繼承的類
要繼承一個類,請使用 :
符號。
在下面的示例中,Car
類 (子類) 繼承了 Vehicle
類 (父類) 的欄位和方法。
示例
class Vehicle // base class (parent)
{
public string brand = "Ford"; // Vehicle field
public void honk() // Vehicle method
{
Console.WriteLine("Tuut, tuut!");
}
}
class Car : Vehicle // derived class (child)
{
public string modelName = "Mustang"; // Car field
}
class Program
{
static void Main(string[] args)
{
// Create a myCar object
Car myCar = new Car();
// Call the honk() method (From the Vehicle class) on the myCar object
myCar.honk();
// Display the value of the brand field (from the Vehicle class) and the value of the modelName from the Car class
Console.WriteLine(myCar.brand + " " + myCar.modelName);
}
}
sealed 關鍵字
如果您不想讓其他類繼承某個類,請使用 sealed
關鍵字。
如果您嘗試訪問 sealed
類,C# 將生成一個錯誤。
sealed class Vehicle
{
...
}
class Car : Vehicle
{
...
}
錯誤訊息將類似如下內容
'Car': 不能從 sealed 型別 'Vehicle' 派生