Interfaces Compared with Classes


Interfaces introduce another category of data types. (They are one of the few categories of types that don't extend System.Object.) Unlike classes, however, interfaces can never be instantiated. An interface instance is accessible only via a reference to an object that implements the interface. It is not possible to use the new operator with an interface; therefore, interfaces cannot contain any constructors or finalizers. Furthermore, static members are not allowed on interfaces.

Interfaces are closer to abstract classes, sharing such features as the lack of instantiation capability. Table 7.1 lists additional comparisons.

Table 7.1. Comparing Abstract Classes and Interfaces

Abstract Classes

Interfaces

Cannot be instantiated independently from their derived classes. Abstract class constructors are called only by their derived classes.

Cannot be instantiated.

Define abstract member signatures that base classes must implement.

Implementation of all members of the interface occurs in the base class. It is not possible to implement only some members within the implementing class.

Are more extensible than interfaces, without breaking any version compatibility. With abstract classes, it is possible to add additional nonabstract members that all derived classes can inherit.

Extending interfaces with additional members breaks the version compatibility.

Can include data stored in fields.

Cannot store any data. Fields can be specified only on the deriving classes. The workaround for this is to define properties, but without implementation.

Allow for (virtual) members that have implementation and, therefore, provide a default implementation of a member to the deriving class.

All members are automatically virtual and cannot include any implementation.

Deriving from an abstract class uses up a subclass's one and only base class option.

Although no default implementation can appear, classes implementing interfaces can continue to derive from one another.


Given that abstract classes and interfaces have their own sets of advantages and disadvantages, you must make a cost-benefit decision based on the comparisons in Table 7.1 in order to make the right choice.




Essential C# 2.0
Essential C# 2.0
ISBN: 0321150775
EAN: 2147483647
Year: 2007
Pages: 185

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net