How to use virtual method to implement an interface

virtual method for interface implementation

To open the possibility for subclass to reimplement members from interface we can add virtual keyword to the implementation.


using System;/* www.j  ava  2 s. co m*/
interface Printable{
    void print();
}

class Shape : Printable{
   public virtual void print(){
     Console.WriteLine("shape");
   }
}

class Rectangle : Shape{
   public override void print(){
     Console.WriteLine("rectangle");
   }
}


class Test
{
    static void Main()
    {

        Shape s = new Shape();
        s.print();

        Rectangle r = new Rectangle();
        r.print();

    }
}

The output:





















Home »
  C# Tutorial »
    Custom Types »




C# Class
C# Struct
C# Interface
C# Inheritance
C# Namespace
C# Object
C# Delegate
C# Lambda
C# Event
C# Enum
C# Attribute
C# Generics
C# Preprocessor