VB.Net中文教程(2) 继承与封装性(3)

页面导航:首页 > 软件编程 > vb.net > VB.Net中文教程(2) 继承与封装性(3)

VB.Net中文教程(2) 继承与封装性(3)

来源: 作者: 时间:2016-02-05 12:32 【

#End Region Protected Sub Form1_Click( ByVal sender As Object,

 

 

#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

  

   Public Sub New()

       MyBase.New()

       Form1 = Me

       This call is required by the Win Form Designer.

       InitializeComponent()

       TODO: Add any initializati

Tags:

文章评论


<