13.2. Implementing More than One InterfaceClasses can derive from only one class (and if it doesn't explicitly derive from a class, then it implicitly derives from Object ).
When you design your class, you can choose not to implement any interfaces, you can implement a single interface, or you can implement two or more interfaces. For example, in addition to IStorable , you might have a second interface, ICompressible , for files that can be compressed to save disk space. If your Document class can be stored and compressed, you might choose to have Document implement both the IStorable and ICompressible interfaces.
Example 13-2 shows the complete listing of the new ICompressible interface and demonstrates how you modify the Document class to implement the two interfaces. Example 13-2. IStorable and ICompressible, implemented by Document
The output looks like this: Creating document with: Test Document Implementing the Read Method for IStorable Implementing Compress Document Status: -1 As Example 13-2 shows, you declare the fact that your Document class will implement two interfaces by adding the second interface to the declaration (in the base list), separating the two interfaces with commas: public class Document : IStorable, ICompressible Once you've done this, the Document class must also implement the methods specified by the ICompressible interface. ICompressible has only two methods, Compress( ) and Uncompress( ) , which are specified as: interface ICompressible { void Compress( ); void Decompress( ); } In this simplified example, Document implements these two methods as follows , printing notification messages to the console: public void Compress( ) { Console.WriteLine("Implementing the Compress Method"); } public void Decompress( ) { Console.WriteLine("Implementing the Decompress Method"); } |