当前位置:编程学习 > VB >>

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

 

 

1. 继承与封装性(Encapsulation)

1.1 公用与私有数据

 

   前面已介绍「封藏性」(Encapsulation) 之观念。即是﹕类别内所定义之资料成员﹐只限于程序成员才能存取之。现在所面临之问题为﹕子类别能否直接存取父类别之资料呢﹖就如同﹕儿女从父母亲继承了财产﹐但能否取用或卖掉继承而来的财产呢﹖如果可以﹐显然违背了「封藏性」之理想。如果不行﹐显然带给程序员莫大之限制。理论上﹐百分之百的封藏性最为完美﹔但应用上﹐若给予子类别若干优待﹐能提高程序之弹性及效率。为了解决此鱼与熊掌不可兼得之困境﹐VB提供三种选择﹕

 

   (1) Public    ──指定某些数据为公用的﹐任何程序皆可直接取用之﹔此时并无任何封藏作用。

   (2) Protected ──指定某些资料为家族公用﹐亦即只有子孙类别内之程序可取用﹐非子孙类别之程序必须呼叫家族内之程序代为存取。

   (3) Private   ──指定某资料为类别私有﹐只限于该类别之程序才可取用。子类别之程序也必须呼叫父类别之程序代为存取﹐此时具百分之百封藏性。

 

   先前介绍「封装性」基本概念时,您已经认识了Public和Private的用意了,至于Protected则配合继承来使用,于是在此特别强调它。

   由于VB向现实妥协﹐开了方便之门﹐无百分之百封藏性﹔所以有些人认为 VB并非完美的 OOP语言。您认为如何呢﹖请看个程序﹕

 

ex01.bas

Imports System.ComponentModel

Imports System.Drawing

Imports System.WinForms

---------------------------------------------------------

Class Person

   Private name As String

   Public age As Integer

   Public Sub New(ByVal na As String, ByVal a As Integer)

       name = na

       age = a

   End Sub

End Class

 

Class Teacher

   Inherits Person

  

   Public salary As Single

   Public Sub New(ByVal na As String, ByVal a As Integer, ByVal sa As Single)

       MyBase.New(na, a)

       salary = sa

   End Sub

   Public Sub modifyAge(ByVal a As Integer)

       age = 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 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 "

     .......

补充:软件开发 , Vb ,
CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,