C# 繼承
繼承(加上封裝和多型性)是面向物件的編程的三個主要特性(也稱為“支柱”)之一, 繼承用于創建可重用、擴展和修改在其他類中定義的行為的新類, 其成員被繼承的類稱為“基類”,繼承這些成員的類稱為“派生類”, 派生類只能有一個直接基類, 但是,繼承是可傳遞的,
基類和派生類
一個類可以派生自多個類或介面,這意味著它可以從多個基類或介面繼承資料和函式,
C# 中創建派生類的語法如下:
<訪問修飾符符> class <基類>
{
...
}
class <派生類> : <基類>
{
...
}
假設,有一個基類(父類) Shape,它的派生類(子類)是 Rectangle:
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;
}
// 派生類
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);
// 列印物件的面積
Console.WriteLine("總面積: {0}", Rect.getArea());
Console.ReadKey();
}
}
}
基類(父類)的初始化
派生類繼承了基類的成員變數和成員方法,因此父類物件應在子類物件創建之前被創建,您可以在成員初始化串列中進行父類的初始化,
using System;
namespace RectangleApplication
{
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("長度: {0}", length);
Console.WriteLine("寬度: {0}", width);
Console.WriteLine("面積: {0}", GetArea());
}
}//end class Rectangle
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("成本: {0}", GetCost());
}
}
class ExecuteRectangle
{
static void Main(string[] args)
{
Tabletop t = new Tabletop(4.5, 7.5);
t.Display();
Console.ReadLine();
}
}
}
C# 多重繼承
多重繼承指的是一個類別可以同時從多于一個父類繼承行為與特征的功能,與單一繼承相對,單一繼承指一個類別只可以繼承自一個父類,
C# 不支持多重繼承,但是,您可以使用介面來實作多重繼承,
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/46957.html
標籤:C#
