Monday, 25 April 2016

Interface and Abstract class


Interface vs. Abstract class
  • Interfaces provide a form of multiple inheritance.
  • A class can extend only one other class.
  • Interfaces are limited to public methods and constants with no implementation.
  • Abstract classes can have a partial implementation, protected parts, static methods, etc.
  • A Class may implement multiple interfaces.
  • In case of abstract class, a class may extend only one abstract class.
  • Interfaces are slower as it requires extra indirection to to find corresponding method in in the actual class.
  • Abstract classes are fast.

Similarities
  • Neither Abstract classes or Interface can be instantiated

When to use Interface or Abstract class ?
Abstract class
  • The advantage of an abstract class is that you can (partially) implement the class.
  • Use abstract Java classes when you want to provide some standard base code but want / need to force the user's of your class to complete the implementation.

Interface
  • If you have a group of classes that you want to call the same methods on; just make them implement the interface and you will be able to program to the interface, rather than one of the individual classes.
  • The advantage of an interface is that you can implement multiple interfaces, whereas you can not extend multiple abstract classes.

"From a design perspective, I tend to favor Interfaces over abstract classes.
They ensure you are not tied to a specific implementation, are simpler to work with when things get complex, and allow you to add to your application by building new classes that implement the interface."                

- Shahnawaz Khan (Blog Author)

No comments:

Post a Comment

Note: only a member of this blog may post a comment.