Polymorphism and Interfaces

Interfaces are the hottest concept in language design. It’s not as if they’re new. COM has had interfaces all along, and Visual Basic version 4 had them behind the scenes. They’re very similar to what C++ calls abstract base classes. But things really started popping when Java incorporated interfaces as a language feature. In fact, the Java literature claims that interfaces are a better replacement for the much maligned concept of multiple inheritance.

Who am I to say that Visual Basic copied Java interfaces? But the new Implements keyword provides essentially the same feature. (Coincidentally, a very similar feature appears in the latest version of Delphi.) Visual Basic’s Implements keyword has a very different syntax than Java’s interface and implements keywords. The Visual Basic version looks a lot like the event syntax, and requires setting extra object variables in situations where Java gets by with type casting.

It’s ironic that Visual Basic gets a feature designed to replace multiple inheritance before it even gets single inheritance. Of course, if avoidance of irony were our chief goal, we wouldn’t choose programming as a profession. In any case, the purpose of Implements is not multiple inheritance, but polymorphism.

Visual Basic version 4 had polymorphism, but the price was exorbitantly high. In order to use polymorphism, clients of polymorphic classes had to receive them as Objects. This worked, but it always resulted in minimal type protection, late binding, and slow operations. I described this crude version of polymorphism in the first edition of this book, but warned against using it for operations that required high performance. The new Implements keyword gives you safe, fast polymorphism. Let’s check it out.