Chapter 7. Interfaces, Casting, and “is” Making classes keep their Promises
Need an object to do a specific job? Use an interface.
Sometimes you need to group your objects together based on the things they can do rather than the classes they inherit from—and that’s where interfaces come in. You can use an interface to define a specific job. Any instance of a class that implements the interface is guaranteed to do that job, no matter what other classes it’s related to. To make it all work, any class that implements an interface must promise to fulfill all of its obligations…or the compiler will break its kneecaps, see?
The beehive is under attack!
An enemy hive is trying to take over the queen’s territory and keeps sending enemy bees to attack her workers. She’s added a new elite Bee subclass called HiveDefender to help defend the hive.
HiveDefender needs a DefendHive method because enemies can attack at any time
We can add a HiveDefender subclass to the Bee class hierarchy by extending the Bee class, overriding its CostPerShift with the amount of honey each defender consumes every shift, and overriding the DoJob method to fly out to the enemy hive and attack the enemy bees.
But enemy bees can attack at any time. We want defenders to be able to defend the hive whether or ...
Get Head First C#, 5th Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.