Overriding and Inheritance in C#

In C# methods are not virtual by default, so if you design some method as overridable, you should specify it as virtual:

class Base 
{
  protected virtual string GetMood() {...}
}

Second, you have to specify that you are going to override method from base class in derived class.

class Derived : Base
{
  protected override string GetMood() {...}
}

If you don't specify "override" keyword, you will get method that hides base type (and warning from compiler to put "new" keyword for the method to explicitly state so).

If you want to stop inheritance chain and disallow further overrides of the method, you should mark method as sealed, like this:

  protected sealed override string GetMood() {...}

You need to use the override keyword to override any virtual or implement any abstract methods.

public class MoodyObject
{
    protected virtual String getMood() 
    { 
        return "moody"; 
    }    
    public void queryMood() 
    { 
        Console.WriteLine("I feel " + getMood() + " today!"); 
    }
}

public class HappyObject : MoodyObject
{
    protected override string getMood()
    {
        return "happy";
    }
}

What I would recommend here is that you probally meant for MoodyObject to be an abstract class. (You'd have to change your main method if you do this but you should explore it) Does it really make sense to be in a moody mode? The problem with what we have above is that your HappyObject is not required to provide an implementation for getMood.By making a class abstract it does several things:

  1. You cannot new up an instance of an abstract class. You have to use a child class.
  2. You can force derived children to implement certain methods.

So to do this you end up:

public abstract class MoodyObject
{
    protected abstract String getMood();

    public void queryMood() 
    { 
        Console.WriteLine("I feel " + getMood() + " today!"); 
    }
}

Note how you no longer provide an implementation for getMood.


As far as I know, in Java all methods are virtual by default. This is not the case with C#, so you need to mark the base class methods with "virtual", e.g. protected virtual string getMood() ... and the overrides with "override", e.g. protected override string getMood()....