Saturday 19 October 2013

Why use abstract class and not interface?

Class which provides some of the functionality required by derived classes, but each derived class additionally requires differing implementation of other functionality, then an abstract class provides a means of defining the common implementation, while leaving the specific behaviors required by derived classes to be made specific to each derived class. 

You can not extends more than one class but you can implements more than one interface

Abstract Class

  • Allows you to leverage the power of using constructors and constructor overriding
  • Restrict the class having multiple inheritance(This is particularly useful if you are designing a complicated API)
  • Instance variables and method implementations
  • Leverage the power of method super calling(Use super to call the parent abstract class's implementation)

Interface

  • Enables multiple inheritance - you can implement n number of interfaces
  • Allows to represent only conceptual methods (No method bodies)
Abstract classes do have a few advantages:
  • they allow you to specify abstract methods with package/protected modifiers
  • they facilitate code re-use
  • via the use of abstract methods and final methods on the super class they allow you to restrict the manner in which your class is subclassed, which can be useful in a wide variety of circumstances
  • code that references classes is generally easier to follow in an IDE (clicking "open declaration" on an abstract class type parameter is usually more useful than on an interface type parameter)

Generally use Interfaces for '-able' clause(as in functionality). Eg:-
  1. Runnable
  2. Observable
Use abstract classes for something like is-a(evolution format). Eg:-
  1. Number
  2. Graphics

No comments:

Post a Comment