abstract method use vs regular methods

Mulder picture Mulder · Apr 9, 2011 · Viewed 9.9k times · Source

I would like to know the difference between two conventions:

  1. Creating an abstract base class with an abstract method which will be implemented later on the derived classes.
  2. Creating an abstract base class without abstract methods
    but adding the relevant method later on the level of the derived classes.

What is the difference?

Answer

Matthew Abbott picture Matthew Abbott · Apr 9, 2011

Much like interfaces, abstract classes are designed to express a set of known operations for your types. Unlike interfaces however, abstract classes allow you to implement common/shared functionality that may be used by any derived type. E.g.:

public abstract class LoggerBase
{
  public abstract void Write(object item);

  protected virtual object FormatObject(object item)
  {
    return item;
  }
}

In this really basic example above, I've essentially done two things:

  1. Defined a contract that my derived types will conform to.
  2. Provides some default functionality that could be overriden if required.

Given that I know that any derived type of LoggerBase will have a Write method, I can call that. The equivalent of the above as an interface could be:

public interface ILogger
{
  void Write(object item);
}

As an abstract class, I can provide an additional service FormatObject which can optionally be overriden, say if I was writing a ConsoleLogger, e.g.:

public class ConsoleLogger : LoggerBase
{
  public override void Write(object item)
  {
    Console.WriteLine(FormatObject(item));
  }
}

By marking the FormatObject method as virtual, it means I can provide a shared implementation. I can also override it:

public class ConsoleLogger : LoggerBase
{
  public override void Write(object item)
  {
    Console.WriteLine(FormatObject(item));
  }

  protected override object FormatObject(object item)
  {
    return item.ToString().ToUpper();
  }
}

So, the key parts are:

  1. abstract classes must be inherited.
  2. abstract methods must be implemented in derived types.
  3. virtual methods can be overriden in derived types.

In the second scenario, because you wouldn't be adding the functionality to the abstract base class, you couldn't call that method when dealing with an instance of the base class directly. E.g., if I implemented ConsoleLogger.WriteSomethingElse, I couldn't call it from LoggerBase.WriteSomethingElse.