What is the difference between a simple base class and abstract class?

peter picture peter · Sep 19, 2013 · Viewed 21k times · Source

I was doing a kind of R&D and am confused with the concept of an abstract class.

What I know about an abstract class is that it may contain concrete methods, and it may contain virtual methods. It may or may not contain an abstract method, and it may contain fields and restricting the direct creation of instances.

But we can achieve all these in a simple base class (an addition of virtual methods will do a lot because a base class with virtual methods which doesn't contain an implementation there and override is same as an abstract method). Then why do we need an abstract class though interface support multiple inheritance and events?

Answer

Servy picture Servy · Sep 19, 2013

But we can achieve all these in a simple baseclass

No, you can't. You can't have a non-abstract class that has abstract methods (methods where the signature is defined, but no implementation is given, thus forcing derived classes to provide an implementation).

Abstract classes exist so that they can provide a combination of implemented methods and abstract methods.

You can attempt to avoid using abstract classes by using concrete implementations that just don't do anything, but it has a number of drawbacks:

  • It doesn't force the caller to override the implementation.
  • It gives the impression that the type and those methods in particular are working, when in fact they are not. By adding the feature of abstract methods and types you prevent the unintended use of an incomplete type by someone who doesn't realize that it's incomplete.
  • It provides a clear contract to sub-classes as to what functionality they need to provide, versus what methods of the base class are working but can optionally be extended.

Also consider non-void methods in a world without abstract. They would need to throw (i.e. NotImplementedException) or return an invalid value (i.e. null). This could be quite a lot worse than a method that just does nothing.