此时﹐salary为类别私有﹐其它类别不得使用。name为家族私有﹐家族外之类别不得使用。age为公用﹐任何类别皆可用。
1.2 公用与私有程序 上节介绍过﹕资料成员有 Private、Protected 及Public之分。同样地﹐程序成员也可分为 Private、Protected 及Public。虽然在应用上﹐程序成员大多定义为Public﹐但必要时﹐也能将过程定义为Private 或 Protected。私有程序和私有资料一样﹐只限于该类别之程序才能呼叫它。例如﹕
'ex04.bas Imports System.ComponentModel Imports System.Drawing Imports System.WinForms '---------------------------------------------------------------------- Class Person Private name As String Private age As Integer Private Sub modifyAge(ByVal a As Integer) age = a End Sub Public Sub New(ByVal na As String, ByVal a As Integer) name = na age = a End Sub Public Sub modify(ByVal na As String, ByVal a As Integer) name = na modifyAge(a) End Sub Public Sub Show() Messagebox.Show("Name: " + name + " Age: " + str(age)) End Sub End Class '------------------------------------------------------------------- Public Class Form1 Inherits System.WinForms.Form
Public Sub New() MyBase.New()
Form1 = Me 'This call is required by the Win Form Designer. InitializeComponent() 'TODO: Add any initialization after the InitializeComponent() call End Sub 'Form overrides dispose to clean up the component list. Public Overrides Sub Dispose() MyBase.Dispose() components.Dispose() End Sub #Region " Windows Form Designer generated code " ....... #End Region Protected Sub Form1_Click( ByVal sender As Object, ByVal e As System.EventArgs) Dim p1 As New Person("David", 25) p1.Show() p1.modify("David Smith", 28) p1.Show() End Sub End Class
此程序输出: Name: David Age: 25 Name: David Smith Age: 45
modifyAge()为私有程序﹐New()及modify()为公用程序。modifyAge()为Person类别之程序成员﹐所以modify()能呼叫modifyAge()。Person类别外之函数不能呼叫modifyAge()。例如﹕在Form1_Click()中﹐可写着 p1.modify()﹐因为modify()为公用程序。但于Form1_Click()内﹐就不可写着 p1.modifyAge()﹐因为modifyAge()为 Private函数。如果放宽对modifyAge()之限制﹐使Person之子类别能呼叫modifyAge()﹐就须定义modifyAge()为 Protected函数﹐如下﹕
'ex05.bas Imports System.ComponentModel Imports System.Drawing Imports System.WinForms '---------------------------------------------------------------------- Class Person Protected name As String Private age As Integer Protected Sub modifyAge(ByVal a As Integer) age = a End Sub Public Sub New(ByVal na As String, ByVal a As Integer) name = na age = a End Sub Public Sub Show() Messagebox.Show("Name: " + name + " Age: " + str(age)) End Sub End Class
Class Teacher Inherits Person
Public Sub New(ByVal na As String, ByVal a As Integer) MyBase.New(na, a) End Sub Public Sub modify(ByVal na As String, ByVal a As Integer) MyBase.name = na MyBase.modifyAge(a) End Sub End Class '------------------------------------------------------------------- Public Class Form1 Inherits System.WinForms.Form
(编辑:aniston)
|