Interfaces and Abstract Classes

In .NET we can think of Interfaces as a contract for behaviour.

Any class that implements the Interface will be required to implement all of the methods defined in the interface. An Interface can only have a list of methods to be implemented by inheriting classes, it can contain no implementation detail.

A class can implement many Interfaces.

Interfaces can be used by many kinds of class. You might create an IFlyable interface, with a single method, Fly. This could be implemented by a Plane class, a Helicopter class a Bird class and so on. There is little to link these class types, but they all Fly.

An abstract class is similar to an Interface, but has a number of important differences. Where we consider the Interface as a contract for behaviour, an abstract class will define what a set of objects is.

An abstract class would be a base for many similar classes. It can contain methods and state data that cannot be captured in an Interface. You could create an Animal class, and contain properties for Height and Weight. You could also add a method Breathe, which would cause the animal to breathe. In the Animal class you can have a simple implementation of the Breathe method, and you can override it in complex child cases (such as a Fish class).

A class can only inherit from a single abstract class.

So, Interfaces describe what an object can do, abstract classes describe what an object is.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s