Overriding Interface Implementations
An implementing class is free to mark any or all of the methods that implement the interface as virtual. Derived classes can override these implementations to achieve polymorphism. For example, a Document class might implement the IStorable interface and mark the Read( ) and Write( ) methods as virtual. The Document might Read( ) and Write( ) its contents to a File type. The developer might later derive new types from Document, such as a Note or EmailMessage type, and he might decide that Note will read and write to a database rather than to a file.
Example 8-4 strips down the complexity of Example 8-3 and illustrates overriding an interface implementation. The Read( ) method is marked as virtual and is implemented by Document. Read( ) is then overridden in a Note type that derives from Document.
Example 8-4. Overriding an interface implementation
using System; namespace overridingInterface { interface IStorable { void Read( ); void Write( ); } // Simplify Document to implement only IStorable public class Document : IStorable { // the document constructor public Document(string s) { Console.WriteLine( "Creating document with: {0}", s); } // Make read virtual public virtual void Read( ) { Console.WriteLine( "Document Read Method for IStorable"); } // NB: Not virtual! public void Write( ) { Console.WriteLine( "Document Write Method for IStorable"); } } // Derive from Document public class Note : Document { public Note(string s) : base(s) { Console.WriteLine( ...Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access