VBA composition for java-like inheritance

狂风中的少年 提交于 2019-12-04 15:00:18

tom shouldn't be declared As Cat in the first place; the feed procedure is superfluous:

Sub Main()    
    Dim tom As IAnimal
    Set tom = New Cat    
    tom.eat    
End Sub

Now, in the Cat class, these members shouldn't need to exist:

'Superclass methods --- I have to explicitly override all methods :(
Public Sub eat()
    super.eat 
    Debug.print "...a fish!"
End Sub

In SOLID/OOP, you code against the interface, not the concrete type - that's why tom is an IAnimal and not a Cat. Being accessed through its IAnimal interface, Cat.eat is entirely redundant, and suggests that a Cat does something an IAnimal doesn't do, which violates SOLID principles: suddenly it becomes relevant that an IAnimal is a Cat, and it shouldn't be, because polymorphism allows IAnimal to be anything, and the Liskov Substitution Principle (LSP - the "L" of "SOLID") says any code that works with an IAnimal should be able to work identically regardless of what implementation of that interface it's given.

Abiding by these principles means that no IAnimal implementation should have a copy of IAnimal members on its default interface (e.g. Cat.eat, vs IAnimal.eat), and that entirely removes your point #2:

  1. re-implements (again) all the methods, to expose them from the subclass, even when override is not necessary.

As for point 1...

  1. re-implement all the methods of the IAnimal interface

That's a compiler requirement, and isn't a VBA quirk: be it in Java, C#, or VBA, you can't say "I'm implementing an interface" ...without implementing its members. Of course Java & C# allow for class inheritance, so your base class could say "I'm implementing an interface", implement all the members, and the derived classes would happily inherit them - but then, that's inheritance, not composition anymore.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!