vb.net中用继承实现多态性2007-05-24 本站 大部分面向对象的程序开发系统都是通过继承来实现多态。比如说跳蚤类和狗类都是从动物类继承过来的。为了突出每一种动物走动的特点,则每一种特定动物类都要重载动物类的"Move"方法。
多态性的问题是因为用户可以需要在还不知道是要对哪种特定动物进行处理的时候,就要调用多种从动物类中派生出来的特定的动物类中的"Move"方法。
在下面的这个TestPolymorphism过程中,用继承来实现多态性:
MustInherit Public Class Amimal "基本类MustOverride Public Sub Bite(Byval What As Object)MustOverride Public Sub Move(ByRef Distance As Double)End ClassPublic Class FleaInherits AmimalOverrides Sub bite(Byval What As Object) "Bite somethingEnd SubOverrides Sub Move(ByRef Distance As Double) distance=Distance+1End SubEnd ClassPublic Class DogInherits AnimalOverrides Public Sub bite(Byval What As Object)"Bite somethingEnd SubOverrides Sub Move(ByRef Distance As Double)distance=Distance+100End SubEnd ClassSub TestPolymorphism()Dim aDog As New Dog()Dim aFlea As New Flea()UseAnimal(aFlea) "Pass a flea object to UseAnimal procedureUseAnimal(aDog)"Pass a Dog object to UseAnimal procedureEnd SubSub UseAnimal(Byval AnAnimal As Animal)Dim distance As Double=0"UseAnimal does not care what kind of animal it is using"The Move method of both the Flea and the Dog are inherited"from the Animal class and can be used interchangeably.AnAniml.Move(distance)If distance=1 Then MessageBox.Show("The animal moved:"&CStr(distance)&_"units,so it must be a Flea.")ElseIf distance>1 Then MessageBox.Show("The animal moved:"&CStr(distance)&_"units,so it must be a Dog.")End IFEnd Sub