VB.NET繼承實(shí)現(xiàn)多態(tài)應(yīng)用方法介紹
最為一款面向?qū)ο蟮木幊陶Z言,VB.NET同樣也可以通過繼承進(jìn)行多態(tài)的實(shí)現(xiàn)。我們今天就為大家介紹一下有關(guān)VB.NET繼承實(shí)現(xiàn)多態(tài)的具體代碼編寫,希望能給大家?guī)硪恍椭?,提高編程效率?/p>
大部分面向?qū)ο蟮某绦蜷_發(fā)系統(tǒng)都是通過繼承來實(shí)現(xiàn)多態(tài)。比如說跳蚤類和狗類都是從動(dòng)物類繼承過來的。為了突出每一種動(dòng)物走動(dòng)的特點(diǎn),則每一種特定動(dòng)物類都要重載動(dòng)物類的"Move"方法。
VB.NET繼承實(shí)現(xiàn)多態(tài)的問題是因?yàn)橛脩艨梢孕枰谶€不知道是要對(duì)哪種特定動(dòng)物進(jìn)行處理的時(shí)候,就要調(diào)用多種從動(dòng)物類中派生出來的特定的動(dòng)物類中的"Move"方法。
在下面的這個(gè)TestPolymorphism過程中,VB.NET繼承實(shí)現(xiàn)多態(tài)的代碼示例:
- MustInherit Public Class Amimal
'基本類- MustOverride Public Sub Bite
(Byval What As Object)- MustOverride Public Sub Move
(ByRef Distance As Double)- End Class
- Public Class Flea
- Inherits Amimal
- Overrides Sub bite(Byval What
As Object)- 'Bite something
- End Sub
- Overrides Sub Move(ByRef
Distance As Double)- distance=Distance+1
- End Sub
- End Class
- Public Class Dog
- Inherits Animal
- Overrides Public Sub bite
(Byval What As Object)- 'Bite something
- End Sub
- Overrides Sub Move(ByRef
Distance As Double)- distance=Distance+100
- End Sub
- End Class
- Sub TestPolymorphism()
- Dim aDog As New Dog()
- Dim aFlea As New Flea()
- UseAnimal(aFlea) 'Pass a flea
object to UseAnimal procedure- UseAnimal(aDog) 'Pass a Dog
object to UseAnimal procedure- End Sub
- Sub 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 IF
- End Sub
VB.NET繼承實(shí)現(xiàn)多態(tài)的相關(guān)代碼編寫就為大家介紹到這里。
【編輯推薦】