Why do we need Abstract Class


Why do we need an Abstract Class, when all the functionality can be achieved
through Base Class and Interfaces?

We write abstract class to define some abstract methods along with, some common methods which can be used by other subclasses. So we can do one thing, the common methods we can define in a Base class. And abstract methods we can define in Interface and the class need it will implement the interface (or the Base class above will implement the
interface).

In this way we can achieve both the functionality. Then why do we need Abstract Classes?

Answer: 

Let us consider a scenario where:


  • We are having a framework with some framework specific methods in core implementing classes, like initialize, uninitialize etc. 
  • We want some work to be implemented in these methods by base and implementing classes both, like 
  • Some common code in base class 
  • Some specific code in extending class 
  • However the sequence of calls for these code segments should be fixed i.e. as per framework assumptions 
Let us take example of initialize method


Class abstract AbstractClass {

Public final void initialize ()
{
      // initialize framework specific items like service locators in
abstract class
// initialize object specific factory in abstract class
// initialize any other resource which is required to be initialized before
any other item of object in abstract class
      InitializeUI ();
// initialize DTO Cache in abstract class
InitializeDTOBindings();
// show UI

}
Public void abstract initializeUI ();
Public void abstract initializeDTOBindings ();

}
Now the extending class is forced to implement the two abstract methods, which framework wants it to extend. However framework still has the control on sequence of method calling and also providing some common implementation. This common implementation is very important with base class, as all the
developers in team may not be mature enough to learn and follow the framework protocol. 

So here abstract class is helping us to enforce the framework protocols.