OOP: Interfaces Ensure Consistent Behavior

Please see my other Object-Oriented Programming (OOP) articles.

Apply Contracts Between Objects with Interfaces

In this article I’ll demonstrate how to ensure consistent behavior when designing an application.

I’m going to build an airport that only accepts types of craft which behave in a consistent manner.

Also, when the airport is in operation, I want to ensure new types of craft may be added without stopping traffic.

First, I’ll create an interface to use as a contract between the airport and all craft it accepts.

Now, I’ll create a base or superclass which all other types of craft will inherit that will use the airport.

Since all other craft will inherit from this class, I can target this type of object in behavior to prevent the need of changing behavior in the future when I add more types of craft (airplane).

Now I’m ready to create my first template off the base class – airplane.

Notice Airplane inherits the base Craft class and also implements the interface – why it must provide its own implementation of Fly().

Now I’m ready to define my airport.

Airport begins by creating a collection of crafts. Note it stores the base class objects types so it can receive any type which inherits the base type – airplanes, helicopters, etc.

Accept() implements the interface so only craft which implement this interface may be accepted – this ensures consistent behavior from all craft at the airport.

Finally, DisplayRosterCount() displays the total number of current craft.

Now I’ll run my console app to see the airport in action.