Thursday, April 25, 2013

Abstract Class vs Interface

This is a very common question that you can come across every Java Interview usually when you are looking for your first job.

Interfaces
  • Interfaces are contracts for what a class can do, but they say nothing about the way.
  • Interfaces can be implemented by any class.
  • An interface is 100% abstract class.
  • No concrete methods are allowed.
  • Can have constants, which are always implicitly public, static and final.
  • A class implementing an interface can be abstract and it doesn't have to implement the interface
  • Interfaces can extend one or more interfaces.
  • Interfaces cannot extend a class.
  • Interface methods must not be static.
Abstract Class
  • An abstract class can never be instantiated. Its sole purpose is to be extended.
  • Methods marked abstract end in a semicolon rather than curly brackets.
  • An abstract class can have both abstract and non-abstract methods.

Interface vs. abstract class
Choosing interfaces and abstract classes is not an either/or proposition. If you need to change your design, make it an interface. However, you may have abstract classes that provide some default behavior. Abstract classes are excellent candidates inside of application frameworks. 

Abstract classes let you define some behaviors; they force your subclasses to provide others. For example, if you have an application framework, an abstract class may provide default services such as event and message handling. Those services allow your application to plug in to your application framework. However, there is some application-specific functionality that only your application can perform. Such functionality might include startup and shutdown tasks, which are often application-dependent. So instead of trying to define that behavior itself, the abstract base class can declare abstract shutdown and startup methods. The base class knows that it needs those methods, but an abstract class lets your class admit that it doesn't know how to perform those actions; it only knows that it must initiate the actions. When it is time to start up, the abstract class can call the startup method. When the base class calls this method, Java calls the method defined by the child class. 

No comments:

Post a Comment