O'Reilly logo

Learning C# by Jesse Liberty

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Overriding Interface Implementations

An implementing class is free to mark any or all of the methods from the interface as virtual. Derived classes can then override or provide new implementations, just as they might with any other virtual instance method.

For example, a Document class might implement the IStorable interface and mark its Read() and Write() methods as virtual. The developer might later derive new types from Document, such as a Note type. While the Document class implements Read() and Write to save to a File, the Note class might implement Read() and Write() to read from and write to a database.

Example 14-6 strips down the complexity of the previous examples and illustrates overriding an interface implementation. In this example, you’ll derive a new class named Note from the Document class.

Document implements the IStorable-required Read() method as a virtual method, and Note overrides that implementation.

Tip

Notice that Document does not mark Write() as virtual. You’ll see the implications of this decision in the analysis section that follows Example 14-6.

The complete listing is shown in Example 14-6.

Example 14-6. Overriding an interface implementation

using System;

namespace OverridingInterfaces
{
    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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required