I would like to know the difference between two conventions:
- Creating an abstract base class with an abstract method
which will be implemented later on the derived classes. - 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?
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.:
In this really basic example above, I’ve essentially done two things:
Given that I know that any derived type of
LoggerBasewill have aWritemethod, I can call that. The equivalent of the above as an interface could be:As an abstract class, I can provide an additional service
FormatObjectwhich can optionally be overriden, say if I was writing aConsoleLogger, e.g.:By marking the
FormatObjectmethod as virtual, it means I can provide a shared implementation. I can also override it:So, the key parts are:
abstractclasses must be inherited.abstractmethods must be implemented in derived types.virtualmethods 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 fromLoggerBase.WriteSomethingElse.