*

*

Java - Importance of Abstract Classes and Interfaces


We all understand what abstract classes and interfaces are, but have we ever tried to understand their importance ? Why do we have abstract classes and interfaces ? and Why don't we just use normal concrete classes in place of them ?

Like Concrete Classes, Abstract classes promotes re-usability of code. Over and above re usability, Abstract classes does nothing but impose a condition to necessarily implement the abstract methods in the sub classes.

To Summarize, Abstract classes are meant for

  • Re usability of Code 
  • Constraint to implement abstract methods 

Similarly Interfaces are meant for 

  • Constraint to implement abstract methods

So the main objective is to put this constraint of implementing the declared methods. 

So the next question is, Why is this regulation ? The answer is somewhat in relation to runtime Polymorphism.

Run Time Polymorphism or Late binding is the mechanism in which function calls are binded to definition during runtime, and we implement it by having Base class reference handling either the object of base class or the sub classes like

Base b = new Derived(); 

where derived class is only known during runtime, may be on the basis of some runtime parameter. For example - Actions in a web application factory framework.

So, to execute the action we need to call the process method of the action class, like

b. process()

but What if we haven't implement the process method in the derived class. This will give the runtime exception - MethodNotFoundException.

This is why the restriction is necessary to give a compile time check if the method is not implemented in the concrete derived class. We can use reference of base class or interface only to handle object of the classes that comply with this restriction or in other sense, extend the abstract class or implement the interface.

Hope it Answers.  

comments powered by Disqus