Home |  JournalSeek |  SoftwareSeek |  GenomeSeek |  Expression |  Developer |  TakeOnIt
Return to Genamics Home

11. Polymorphism

Virtual methods allow object oriented languages to express polymorphism. This means a derived class can write a method with the same signature as a method in its base class, and the base class will call the derived class's method. By default in Java, all methods are virtual. In C#, like C++, the virtual keyword must be used so that the method will be called by the base class.

In C#, it is also required that the override keyword is needed to specify that a method should override a method (or implement an abstract method) of its base class.

Class B {
    public virtual void foo () {}
}

Class D : B {
    public override void foo () {}
}

Attempting to override a non-virtual method will result in a compile-time error unless the "new" keyword is added to the declaration, indicating the method is intentionally hiding the base class's method.

Class N : D {
    public new void foo () {}
}

N n = new N ();
n.foo(); // calls N's foo
((D)n).foo(); // calls D's foo
((B)n).foo(); // calls D's foo

In contrast to both C++ and Java, requiring the override keyword makes it more clear what methods are overridden when looking at source code. However, requiring the use of the virtual method has its pros and cons. The first pro is that is the slightly increased execution speed from avoiding virtual methods. The second pro is to make clear what methods are intended to be overridden. However, this pro can also be a con. Compare the default option of leaving out a final modifier in Java vs leaving out a virtual modifier in C++. The default option in Java may make your program slightly less efficient, but in C++ it may prevent extendibility, albeit unforeseen, by the implementer of the base class.

12. Interfaces

Interfaces in C# are similar to Java interfaces, but can be used with greater flexibility. A class may optionally "explicitly" implement an interface:

public interface ITeller
{
    void Next ();
}

public interface IIterator
{
    void Next ();
}

public class Clark : ITeller, IIterator
{
    void ITeller.Next () {
    }
    void IIterator.Next () {
    }
}

This gives a class two benefits. First, a class can implement several interfaces without having to worry about naming conflicts. Second, it allows a class to "hide" a method if it is not useful for general users of the class. Explicitly implemented methods are invoked by type-casting a class to the interface required:

Clark clark = new Clark ();
((ITeller)clark).Next();


Previous     Next


C# 3.0 in a Nutshell (April 2007) - by Joseph Albahari and Ben Albahari.









Add To Favorites
Email This Page



Side Panel
Privacy Policy About Us Contact Us