習題一:向量物件
習題二:矩陣物件

在傳統的結構化程式設計 (像是 C, Fortran, Pascal) 當中,我們用函數來處理資料,但是函數與資料是完全區隔開來的兩個世界。然而,在物件導向當中,函數與資料被合為一體,形成一種稱為物件的結構,我們稱這種將函數與資料放在一起的特性為「封裝」。

以下我們將以矩形物件為範例,說明 C# 當中的封裝語法,以及物件導向中的封裝概念。

範例一:封裝 — 將函數與資料裝入物件當中

using System;
class Rectangle
{
    double width, height;
    double area()
    {
        return width * height;
    }
    public static void Main(string[] args)
    {
        Rectangle r = new Rectangle();
        r.width = 5.0;
        r.height = 8.0;
        Console.WriteLine("r.area() = " + r.area());
    }
}
	

執行結果

r.area() = 40
	

修改進化版

由於上述物件與主程式混在一起,可能容易造成誤解,因此我們將主程式獨立出來,並且新增了一個 r2 的矩形物件,此時程式如下所示。

using System;
class Rectangle
{
    public double width, height;
    public double area()
    {
        return width * height;
    }
}
class Test
{
    public static void Main(string[] args)
    {
        Rectangle r = new Rectangle();
        r.width = 5.0;
        r.height = 8.0;
        Console.WriteLine("r.area() = " + r.area());
        Rectangle r2 = new Rectangle();
        r2.width = 7.0;
        r2.height = 4.0;
        Console.WriteLine("r2.area() = " + r2.area());
    }
}
	

執行結果:

r.area() = 40
r2.area() = 28
	

範例二:加上建構函數

using System;
class Rectangle
{
    double width, height;
    public Rectangle(double w, double h)
    {
        width = w;
        height = h;
    }
    public double area()
    {
        return width * height;
    }
    public static void Main(string[] args)
    {
        Rectangle r = new Rectangle(5.0, 8.0);
        Console.WriteLine("r.area() = " + r.area());
    }
}
	

執行結果

r.area() = 40
	

範例二:加上建構函數 — 同時有 0 個與兩個引數

using System;
class Rectangle
{
    public double width, height;
    public Rectangle() { }
    public Rectangle(double w, double h)
    {
        width = w;
        height = h;
    }
    public double area()
    {
        return width * height;
    }
}
class Test
{
    public static void Main(string[] args)
    {
        Rectangle r = new Rectangle(5.0, 8.0);
        Console.WriteLine("r.area() = " + r.area());
        Rectangle r2 = new Rectangle();
        r2.width = 7.0;
        r2.height = 4.0;
        Console.WriteLine("r2.area() = " + r2.area());
    }
}
	

文章轉載:陳鍾誠 (2010年10月19日),(網頁標題) C# 語言中的物件封裝 (Encapsulation),(網站標題) 免費電子書:C# 程式設計,2010年10月19日,取自 http://cs0.wikidot.com/encapsulation ,網頁修改第 8 版。

arrow
arrow

    Johnson峰 發表在 痞客邦 留言(0) 人氣()