但我想知道是否有更有效和简洁的方法来实现这一点。
考虑一下这个小测试用例。
陆地生物
'declaration
Public Sub eat()
End Sub
Public Sub breathe()
End Sub
Implements IAnimal
' method implementation
Private Sub IAnimal_eat()
Debug.Print "I'm eating something..."
End Sub
Private Sub IAnimal_breathe()
Debug.Print "I'm brething..."
End Sub
猫cls:动物的一个亚纲
Private super As IAnimal
Implements IAnimal
Private Sub Class_Initialize()
Set super = New Animal
End Sub
'#------------------------------------------------
' methods called when object is accessed as an IAnimal implementor.
' I HAVE TO re-implement all of them also here in the subclass (in java I don't need to. It's sufficient to implement them in the superclass)
Private Sub IAnimal_eat()
Me.eat
End Sub
Private Sub IAnimal_breathe()
Me.breathe
End Sub
'#--------------------------------------------------
' subclass-only methods
' To access those methods I MUST DECLARE the object as Cat (Dim tom as Cat)
Public Sub meow()
Debug.Print "meow..."
End Sub
'#------------------------------------------------
' superclass methods
' Since I need to declare the cat object as a Cat (see above)
' I'm FORCED TO explicitly re-implement all of the superclass methods,
' even those that I don't need to override
' otherwise I can't access them
'@Override
Public Sub eat()
Debug.print "I'm eating a fish!"
End Sub
'I'm forced to re-implement also this method, in order to use it directly on a *Cat* object
'@Unnecessary-Override
Public Sub breathe()
super.breathe
End Sub
测试.bas
Sub Main()
Dim snowball As IAnimal
Set snowball = New Cat
Dim tom As Cat
Set tom = New Cat
snowball.meow 'ERROR Method or data member not found
tom.meow '
' creates a Dog, another subclass of Animal
Dim pluto As Dog
Set pluto = New Dog
'create a collection for all my animals
Dim myPets As Collection
Set myPets = New Collection
myPets.Add tom
myPets.Add pluto
Call feed(myPets) '
'I 'm eating a fish
'meow...
'I 'm eating a bone
'woof...
End Sub
' a routine for showing how to manage an heterogeneous collection of animals
Sub feed(animals As Collection)
For Each a In animals
a.eat
If TypeOf a Is Cat Then
a.meow
End If
If TypeOf a Is Dog Then
a.woof
End If
Next
End Sub
打电话给
eat()
方法对猫和狗的对象和
具有特定的重写行为
仅子类方法
(就像
meow()
)
通过
异质动物群
给一个
feed
子例程,它可以“安全地”调用动物超类方法,并根据动物子类触发特定代码
这看起来很有效,但却很麻烦:假设你需要实现许多动物子类(狗、鸟、犰狳、鸭嘴兽、恶魔……)。
上面的模式迫使您:
在所有子类上重新实现IAnimal接口的所有方法
重新实现(再次)所有方法,从子类中公开它们,即使不需要重写。这是必需的,特别是如果您还想访问仅子类的方法。
所以问题是:是否有一种更高效/简洁的方法来实现这个示例(并限制每个子类的代码重写)?