Chapter 6: Using Polymorphism via Interfaces
Overview
Chapter 5, “Understanding Polymorphism,” introduced the concept of polymorphism, a fundamental concept underlying object-oriented programming. Polymorphism is when objects implement similar functionality in different ways, and the user of the objects doesn’t necessarily know about these different implementations.All of the examples in the previous chapter demonstrated polymorphism though class inheritance. An ancestor class defined the baseline functionality, and one or more subclasses augmented or changed that functionality. You can achieve polymorphism by declaring a variable of the ancestor type. This variable can refer to any of the subclasses, yet the code at the scope of this variable declaration doesn’t need to know to which subclass it’s pointing.Class inheritance isn’t the only way to achieve polymorphism. A second technique is through the use of a class interface. An interface declares properties, events, and methods just like a class does, but an interface doesn’t implement any of these members through code. Instead, the interface simply lists the members that comprise it.Previous chapters unofficially introduced the concept of interfaces while describing key classes in the game examples. Chapter 2, “Writing Your First Game, Again,” described the Die class in terms of its public interface. Chapter 4, “More OOPing Around,” did the same thing for the TileData and WavFile classes. To reiterate, discussing a class in terms of its public interface is a good way to learn what a class does without having to pay attention to how it does it. And learning what a class does is the important part because the user of a class needs to learn only the tasks that it accomplishes to use it. He doesn’t need to know about the implementation details (the “how”) of that class.I’m not the only one who thinks that separating class interfaces from implementation is a useful learning tool. Most object-oriented languages have the concept of class interfaces built into them. Chapter 4, “More OOPing Around,” introduced a class interface built into the .NET Framework—the IComparable interface. You’d usually use this interface on an object that needs to be sorted in a specific sort order. If you’ll recall back that far, you’ll remember that you needed to sort the four tile classes used in the DeducTile Reasoning game in top-to-bottom order on the screen so that they could be properly compared against the solution that the player was trying to guess.
In this chapter, you’ll write two games, Tic-Tac-Toe and Reversi, to practice implementing polymorphism via interfaces.