Wednesday, December 10, 2003

Interface and Abstract Class - Part 3

When to use an Interface

The most obvious place you'd need to use an interface rather than an abstract class is when you need to use the functionality defined in the interface across many different classes. For example, one of the techniques in Java for implementing threads is the Runnable interface, which has a single "run()" method. It is a method that will be used by who knows how many different classes so it is best implemented as an interface.

Next would be when you know you are going to have to derive things needed in your classes from several sources. Classes can only inherit from one parent class but can implement multiple interfaces. For example, the SqlCommand class in .NET has to be a child of the Component class but it also needs to implement standard methods for database commands and methods needed so it can be cloned. So it inherits from the Component class and implements the IDbCommand and ICloneable interfaces.

There are situations in some languages where you cannot use inheritance, such as in .NET when you are defining a structure. For example, the Int32 structure in .NET implements three interfaces, IComparable, IFormattable and IConvertible.

The last place you would use an interface is similar to the first rule. You would use an interface where you don't need (or don't want) to inherit from a base class. For example, you want a set of "command" classes to run the piece of functionality you have encapsulated in them, you have one that runs an FTP upload, another runs a database query, another copies some files across the network, etc. They are not similar enough to create a super-class so instead you would use an interface so they provide a standard method for accessing their functionality.

No comments: