日期:2009-04-11  浏览次数:20485 次

主题: 重新定义(Overriding)程序


?????????? 内容 ??????????
v 1. 重新定义程序









1. 重新定义(Override)程序

在应用上﹐常见如下之情况﹕子类别从父类别继承之程序﹐并不合乎子类别之需要。此时可设计新程序取代之。


图1、程序成员之重新定义

例如﹐SalesPerson类别含有Bonus()程序﹔SalesManager由 SalesPerson继承而得Bonus()程序。Bonus()能计算销售人员之红利。然而﹐一般销售员与销售经理之红利计算方法不同﹔所以﹐SalesPerson之Bonus()显然并不适用于SalesManager。这SalesManager类别必须定义适用的Bonus()求算销售经理之红利。子类别不满意继承之程序而自行定义程序取代之﹐此情形称为「再定义」(Redefinition)或「重新定义」(Overriding)。自行定义程序与继承程序之名称相同。请看个程序﹕

'ex01.bas
Imports System.ComponentModel
Imports System.Drawing
Imports System.WinForms
'-----------------------------------------------------------------------------------------
Class SalesPerson
Protected totalSales As Double
Public Sub New(ByVal t As Double)
totalSales = t
End Sub
Public Overridable Function Bonus() As Double
Bonus = totalSales * 0.008
End Function
End Class

Class SalesManager
Inherits SalesPerson
Public Sub New(ByVal t As Double)
MyBase.New(t)
End Sub
Public Overrides Function Bonus() As Double
Bonus = totalSales * 0.008 + 1000
End Function
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 Jim As New SalesPerson(50000)
Messagebox.Show("Jim's Bonus: " + str(Jim.Bonus()))
Dim Tom As New SalesManager(45000)
Messagebox.Show("Tom's Bonus: " + str(Tom.Bonus()))
End Sub
End Class

此程序输出如下﹕ Jim's bonus: 400
Tom's bonus: 1360

因Jim为SalesPerson类别之对象﹐则Jim.Bonus()所指的是SalesPerson之Bonus()程序。SalesManager类别继承此Bonus()﹐且自己定义新的Bonus()程序。此新程序取代了继承之程序。因之﹐Alvin.Bonus()是指SalesManager自己定义之Bonus()程序。
「重新定义」(Overriding)的过程中﹐必定也产生「重复定义」(Overloading) 之现象。前者是针对「父子」类别之间﹐子类别有「修正」(Refinement)或「取代」(Replacement) 之意味时﹐才定义同名称之程序来取代父类别之程序。至于重复定义则范围较广﹐在类别内也能重复定义程序﹐父子类别之间也能重复定义程序﹐甚至互为独立的两类别之间也能发生重复定义之现象﹔重复定义之后新程序与原程序之间﹐在「涵义」(Semantic)上仅类似,但并不必然相同,例如Bonus(ByVal y As Year)与Bonus(ByVal y As Employee)两者涵义不尽相同。
然而重新定义程序﹐例如上述的 SalesPerson例子中﹐父类别SalesPerson.Bonus()和子类别SalesManager.Bonus()皆表示同一涵义──求算红利﹐只是计算方法不同罢了。因之﹐「重新定义」着眼于以不同的执行过程来取代父类别之程序﹐但新旧程序之间﹐具有一致的意图。盼您能区分这易于混淆的概念。请再看个程序:

'ex02.bas
Imports System.ComponentModel
Imports System.Drawing
Imports System.WinForms

'--------------------------------------------------------------------------------------
Public Class Person
Private name As String
Private age As Integer
Public Sub New(ByVal na As String, ByVal a As Integer)
name = na
age = a
End Sub
Public Function birthDay() As Integer
birthDay = 2001 - age
End Function
Public Overridable Sub Display()
Messagebox.Show("Name: " + name +