Tuesday, January 21, 2014

Recommendation for when to use Interface or Abstract base class.




Interface:

Interface is a contract with the class that class will provide the implementation of all the methods or property declared in an Interface.

·         Interface will only contain declaration of the methods or property.

·         Class can implement multiple interfaces.

·         If a class wants to inherit from another class then that class should precede interface implementation.

Example:

Class A : BClass, NewInterface

{

}

Abstract Base Class:

Abstract class is a contact with the inheriting class that inheriting class will provide the implementation of all the abstract methods and properties in defined in the abstract class.

·         A class can inherit only one class.

·         Abstract class can contain both abstract method and implemented methods.

·         If a class inheriting from abstract class does not provide the implementation of all the abstract methods in abstract class, then that class has be marked with abstract keyword.

When to use Abstract base class and when to use Interface

·         If you module or component will undergo versioning in future then it is better to use abstract base class. If a new version of a component is introduced then by updating the base class all the inheriting class will automatically get updated. If you have used interface and a new version is introduced then a new interface need to be created.

·         Use abstract base class for commonly related classes. Interface is used to provide common functionality for unrelated classes.

·         Interface is best suited for small set of functionality, whereas for large modules abstract base class is useful.

·         Abstract base class provides partially implementation functionality for your classes, whereas interfaces provide no implementations for its members, it is implementing class responsibility to provide complete implementation of all the members of an interface.

No comments:

Post a Comment