物件導向
Object-Oriented Programming, OOP,物件導向程式設計。- Object是Class的Instance。
- Class是Object的定義。描述Object的組成與功能。
- Object使用前必須建立Class的Object(Instance)(使用New)。
真正被用來處理問題的是Object,而Class決定了Object的行為。
物件導向範例
01 | Public Class Student |
02 |
03 | Private _name As String |
04 | Private _id As String |
05 |
06 | Sub New () |
07 | _name = "無名" |
08 | End Sub |
09 |
10 | Sub New ( ByVal name As String ) |
11 | _name = name |
12 | End Sub |
13 |
14 | Sub New ( ByVal name As String , ByVal id As String ) |
15 | _name = name |
16 | _id = id |
17 | End Sub |
18 |
19 | Public Property Name As String |
20 | Get |
21 | Return _name |
22 | End Get |
23 | Set ( ByVal value As String ) |
24 | If value.Length > 0 Then |
25 | _name = value |
26 | End If |
27 | End Set |
28 | End Property |
29 |
30 | Public Property id As String |
31 | Get |
32 | Return _id |
33 | End Get |
34 | Set ( ByVal value As String ) |
35 | If value.Length > 0 Then |
36 | _id = value |
37 | End If |
38 | End Set |
39 | End Property |
40 | End Class |
在程式碼中必須先初始化(New),然後才能存取。
01 | Public Class _Default |
02 | Inherits System.Web.UI.Page |
03 |
04 | Protected Sub Page_Load( ByVal sender As Object , ByVal e As System.EventArgs) Handles Me .Load |
05 | Dim s001 As New Student |
06 | Dim s002 As New Student( "Bruce" ) |
07 | Dim s003 As New Student( "Sherry" , "S201010003" ) |
08 |
09 | '無名 |
10 | Response.Write(s001.Name.ToString()) |
11 | 'Bruce |
12 | Response.Write(s002.Name.ToString()) |
13 | 'S201010003 |
14 | Response.Write(s003.id.ToString()) |
15 | End Sub |
16 | End Class |
物件導向的三大特性
- 封裝
將程式碼包裝成為Class以提供特定功能的一種過程。好處:程式碼共用。 - 繼承
Class可透過Inheritance(繼承)來擴充(或修改)內容。 - 多型
在執行階段,定義可供用戶端程式碼交換使用,具有不同功能但名稱完全相同之方法或屬性的Class。
沒有留言:
張貼留言
感謝您的留言,如果我的文章你喜歡或對你有幫助,按個「讚」或「分享」它,我會很高興的。