- It is a contract not a class, so cannot instantiated. You can inherited class from multiple interface.
- It is not whole entity but part of entity behavior.
- Once you create interface and thousand of classes inheriting, you cannot change it. If you change, all the classes needs to recompile
- If you change interface, all classes inheriting it, should also make changes accordingly
- Try to create interface with at most one contract. For more contract, create inherited interface. For e.g. IEnumerable, ICountable and if need both, create inherited interface ICollection : IEnumerable, ICountable. This is not kind of rule but best practice to use interface.
- Use interface carefully. You design will not be flexible.
- If a class is not a type of another class but they have common function, use interface. Example: FullTimeStaff and Customer should not come from the same base class but they may have common function, e.g. discountRate; in this case, interface is more appropriate.
Abstract Class
- It is class with implementation or without implementation. It cannot instantiated but can inherited. You cannot inherit multiple abstract classes.
- It defines whole entity. If you need default implementation for all inherited classes, use abstract class instead of interface.
- With all empty methods, Abstract class is same as interface
- You can make changes in abstract class and inherited class will work fine most of the time without recompile.
- Good thing is , you can add functionality from it and all classes inherited from it will automatically get that functionality.
- Bad thing is, inherited class can assume wrongly that this method is implemented in base class but it might be possible that it is not implemented or implemented differently.
- If a class is a type of another class, use abstract class because abstract class is for inheritance. Example: PartTimeStaff and FullTimeStaff is a type of Staff.
Here are some recommendations to help you to decide whether to use an interface or an abstract class to provide polymorphism for your components.
If you anticipate creating multiple versions of your component, create an abstract class. Abstract classes provide a simple and easy way to version your components. By updating the base class, all inheriting classes are automatically updated with the change. Interfaces, on the other hand, cannot be changed once created. If a new version of an interface is required, you must create a whole new interface.
If the functionality you are creating will be useful across a wide range of disparate objects, use an interface. Abstract classes should be used primarily for objects that are closely related, whereas interfaces are best suited for providing