Select whether to design the function as an interface or an abstract class (mustinherit in Visual Basic ).
Class) is sometimes a difficult task. An abstract class is a class that cannot be instantiated but must be inherited from it. Abstract classes can be fully implemented, but more commonly, they are partially implemented or not implemented at all, so as to encapsulate
Function. For more information, see abstract classes.
On the contrary, an "interface" is a fully abstract set of members and can be seen as defining contracts for operations. The implementation of interfaces is left to developers.
Interfaces and abstract classes are useful for component interaction. If a method requires an interface in the form of a parameter, any object implementing this interface can be used in this parameter. For example:
'Visual basic
Public sub spin (byval widget as iwidget)
// C #
Public void spin (iwidget)
This method can accept any object that implements iwidget as a widget parameter, even if the implementation of iwidget may be very different. Abstract classes also allow this polymorphism, but note the following:
Classes may only inherit from a base class, so if you want to use abstract classes to provide polymorphism for a group of classes, these classes must all inherit from that class.
Abstract classes may also provide implemented members. Therefore, you can use abstract classes to ensure that a specified number of functions are the same, but you cannot use interfaces to do so.
Here are some suggestions to help you decide whether to use interfaces or abstract classes to provide polymorphism for components.
If you want to create multiple versions of a component, create an abstract class. Abstract classes provide a simple way to control component versions. By updating the base class, all inheritance classes are automatically updated with the change. On the other hand, the interface cannot be changed once it is created. If you need a new version of the interface, you must create a new interface.
If the created function is used across a wide range of different objects, the interface is used. Abstract classes are mainly used for closely related objects, and interfaces are most suitable for providing general functions for irrelevant classes.
If you want to design small and concise functional blocks, use interfaces. If you want to design a large functional unit, use an abstract class.
If you want to provide common implemented functions among all the implementations of a component, use an abstract class. Abstract classes allow partial implementation classes, while interfaces do not include the implementation of any member.