In this post I will review when Abstract Classes can be used over Interfaces and vice versa. To begin I start with a definition for Abstract Class and Interface. Then I outline the features and then finish out this post with the pressing question: When should Abstract Classes (or vice versa) be used over Interfaces? In a later post I will provide an example of Interfaces used in Booky.
Before we explore Abstract classes and interfaces let’s define them using Microsoft’s MSDN definitions:
Abstract Classes
They are classes that cannot be instantiated, and are frequently either partially implemented, or not at all implemented. See http://msdn.microsoft.com/en-us/library/k535acbf(v=VS.71).aspx
An abstract class provides a common definition of a base class that multiple derived classes can share.
Interfaces
An interface defines a contract. A class or struct that implements an interface must adhere to its contract. See http://msdn.microsoft.com/en-us/library/87d83y5b(v=vs.71).aspx An interface contains definitions for a group of related functionalities that a class or a struct can implement.
Let’s explore the features of Abstract Classes and Interfaces before we determine the best or optimal time to use one over the other.
Interface Features
- Members are automatically public
- May contain properties, methods, events and indexers.
- An interface can inherit from one or more base interfaces
- Interfaces can be implemented by classes and structs.
Abstract Class Features
- Abstract class cannot be instantiated.
- Members have access modifiers (i.e. public, private)
- May contain fields, properties, constructors, destructors, methods, events and indexers.
- It is not possible to modify an abstract class with the sealed modifier, which means that the class cannot be inherited.
- A non-abstract class derived from an abstract class must include actual implementations of all inherited abstract methods and accessors.
When should Abstract Classes (or vice versa) be used over Interfaces?
A comparison between the two (fix with full name)
Comparison
Abstract Classes | Interfaces |
- They may contain implementation code | - They not contain implementation code |
- They may only inherit from a single base class | - They may implement any number of interfaces |
Use Abstract Classes when you have common shared implementation code. For example if your component requirement has shared functionality among objects then abstract classes may be a candidate for consideration when designing the system.
Use Interfaces when the functionality you are creating will be used across a wide range of objects. When create small pieces of functionality then interfaces are a good choice.
No comments:
Post a Comment